Unity IOC容器以及如何解析同一接口的不同实例 [英] Unity IOC container and how to resolve different instances of the same interface
问题描述
我有一个统一的容器,可以像这样在其中注册类型:
I have a unity container that I am registering types within like so:
IUnityContainer container = new UnityContainer()
.RegisterType<ITaxAuthorityRateService, TaxAuthorityPopulationRateService>( "PopulationRate" )
.RegisterType<ITaxAuthorityRateService, TaxAuthorityBusinessLicenseRateService>( "BusinessLicenseRate" );
然后,我还想注册2个不同的服务,这些服务在其构造函数中使用ITaxAuthorityRateService变量.两种服务都需要从ITaxAuthorityRateService派生的不同类.我该如何处理这种情况?
Then I also want to register 2 different services that take a ITaxAuthorityRateService variable in their constructor. Both services need a different class that derives from ITaxAuthorityRateService. How can I handle that situation?
推荐答案
好,我知道了.在注册过程中保持名称相同是正确的("PopulationRate"和"BusinessLicenseRate").我要做的就是在每个服务的构造函数中向ITaxAuthorityRateService参数添加一个属性,如下所示:
Ok I figured it out. Keeping the names the same during registration is correct ("PopulationRate" and "BusinessLicenseRate"). All I had to do was add an attribute to the ITaxAuthorityRateService parameter within the constructor of each service like so:
Service1构造函数参数:
Service1 constructor parameter:
[Dependency( "BusinessLicenseRate" )]
ITaxAuthorityRateService rateService
Service2构造函数参数:
Service2 constructor parameter:
[Dependency( "PopulationRate" )]
ITaxAuthorityRateService rateService
然后每个服务都收到正确的ITaxAuthorityRateService实例.
And then each service received the correct ITaxAuthorityRateService instance.
这篇关于Unity IOC容器以及如何解析同一接口的不同实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!