1

我正在使用结构映射 IOC 容器我在这里没有使用默认名称约定的扫描。

公共接口 ICompanyRepository

{

    IEnumerable<Company> GetAll();

    Company Get(int id);

    Company Add(Company item);


    bool Update(Company item);

    bool Delete(int id);


}

public class Company1: ICompanyRepository
{
   // Proivide implementation for all interface  methods
}

public class Company2: ICompanyRepository
{
   // Provide implementation for all interface  methods

//Class Company2 will also have new method called DisplayLog
    public void DisplayLog()
    {
        //To do
    }
}

我正在尝试在我的客户控制器类中使用结构映射来实现 DI,我如何告诉我需要调用公司 1 的方法或调用公司 2 的方法?

_.Scan(x =>
     {
        x.TheCallingAssembly();

        x.AddAllTypesOf<ICompanyRepository>();

        // or

    });

我的代码:私有只读 ICustomerRepository customerRepository;

    public CustomerController(ICustomerRepository CustomerRepository)
    {
        customerRepository = CustomerRepository;
    }


    // GET: Customer  
    public ActionResult Index()
    {
        var customers = customerRepository.GetAll
       //Here i need to be specfic telling i need to call company1 or company2 class methods ?
        return View(customers);
    }
4

1 回答 1

-1

如果您有同一个接口的两个具体实现,您可以使用 StructureMap 的命名实例,以便它知道要构建哪一个。

// Repo1
public class CompanyRepository1: ICompanyRepository
{
}

// Repo2
public class CompanyRepository2: ICompanyRepository
{
}

// Controller
public CompanyController(ICompanyRepository companyRespository2)
{
    _companyRepository2 = companyRespository2;
}

// StrucureMap registration
For<ICompanyRepository>().Use<CompanyRepository1>().Named("companyRepository1");
For<ICompanyRepository>().Use<CompanyRepository2>().Named("companyRepository2");
于 2018-03-08T04:34:46.437 回答