Unity IOC容器以及如何解析同一接口的不同实例

Rob*_*ood 1 ioc-container unity-container

我有一个统一容器,我正在这样注册类型:

    IUnityContainer container = new UnityContainer()
.RegisterType<ITaxAuthorityRateService, TaxAuthorityPopulationRateService>( "PopulationRate" )
.RegisterType<ITaxAuthorityRateService, TaxAuthorityBusinessLicenseRateService>( "BusinessLicenseRate" );
Run Code Online (Sandbox Code Playgroud)

然后我还要注册2个不同的服务,这些服务在其构造函数中包含一个ITaxAuthorityRateService变量.两种服务都需要一个派生自ITaxAuthorityRateService的不同类.我该如何处理这种情况?

Rob*_*ood 9

好吧我明白了.在注册期间保持名称相同是正确的("PopulationRate"和"BusinessLicenseRate").我所要做的就是在每个服务的构造函数中为ITaxAuthorityRateService参数添加一个属性,如下所示:

Service1构造函数参数:

[Dependency( "BusinessLicenseRate" )]
ITaxAuthorityRateService rateService
Run Code Online (Sandbox Code Playgroud)

Service2构造函数参数:

[Dependency( "PopulationRate" )]
ITaxAuthorityRateService rateService
Run Code Online (Sandbox Code Playgroud)

然后每个服务都收到了正确的ITaxAuthorityRateService实例.