Unity IOC容器以及如何解析同一接口的不同实例
我有一个统一容器,我在其中注册类型,如下所示:
IUnityContainer container = new UnityContainer()
.RegisterType<ITaxAuthorityRateService, TaxAuthorityPopulationRateService>( "PopulationRate" )
.RegisterType<ITaxAuthorityRateService, TaxAuthorityBusinessLicenseRateService>( "BusinessLicenseRate" );
然后我还想注册 2 个不同的服务,这些服务在其构造函数中采用 ITaxAuthorityRateService 变量。这两种服务都需要派生自 ITaxAuthorityRateService 的不同类。我该如何处理这种情况?
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" );
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我想通了。注册期间保持名称相同是正确的(“PopulationRate”和“BusinessLicenseRate”)。我所要做的就是向每个服务的构造函数中的 ItaxAuthorityRateService 参数添加一个属性,如下所示:
Service1 构造函数参数:
Service2 构造函数参数:
然后每个服务都会收到正确的 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 constructor parameter:
Service2 constructor parameter:
And then each service received the correct ITaxAuthorityRateService instance.