当我尝试返回Sales Data时,我有以下代码返回null。如果我删除了employee的其他构造函数,它就可以工作,所以我相信它是构造函数注入问题。
我该如何处理这种注射?
存储库:位于单独的项目中
public class CompanyRepository : ICompanyRepository, IDisposable
{
public CompanyRepository()
{
}
private readonly IEmployeeRepository _employeeRepository;
public CompanyRepository(IEmployeeRepository parameter)
{
_employeeRepository = parameter;
}
//fails never hits this
private readonly ISalesRepository _salesRepository;
public CompanyRepository(ISalesRepository parameter)
{
_salesRepository = parameter;
}
}
MVC 5控制器:
[HttpGet]
public ActionResult Create()
{
//works
var a = _CompanyRepository.GetCompanyData();
//works
var b = _CompanyRepository.GetEmployeeData();
//fails
var c = _CompanyRepository.GetSalesData();
//return view etc
}
App_Start Unity.Config
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
container.RegisterType<ICompanyRepository, CompanyRepository>();
//this one is failing
container.RegisterType<ICompanyRepository, CompanyRepository>(new InjectionConstructor(new ResolvedParameter<SalesRepository>()));
container.RegisterType<ICompanyRepository, CompanyRepository>(new InjectionConstructor(typeof(EmployeeRepository)));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
我刚刚使用但它无法正常使用
container.RegisterType<ICompanyRepository, CompanyRepository>(new InjectionConstructor(typeof(SalesRepository)));
container.RegisterType<ICompanyRepository, CompanyRepository>(new InjectionConstructor(typeof(EmployeeRepository)));
答案 0 :(得分:2)
您应该为您的InjectionConstructor注册命名
container.RegisterType<ICompanyRepository, CompanyRepository>("salesRep", new InjectionConstructor(new ResolvedParameter<SalesRepository>()));
container.RegisterType<ICompanyRepository, CompanyRepository>("employeeRep",new InjectionConstructor(new ResolvedParameter<EmployeeRepository>()));
然后像这样解决
var salesRep = container.Resolve<ICompanyRepository>( "salesRep" );
var employeeRep = container.Resolve<ICompanyRepository>( "employeeRep" );
解决的另一种方法是将构造函数更改为
public CompanyRepository([Dependency("employeeRep")]IEmployeeRepository parameter)
public CompanyRepository([Dependency("salesRep")]ISalesRepository parameter)
然后使用DependencyResolver