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

发布于 2024-08-23 02:30:33 字数 443 浏览 6 评论 0原文

我有一个统一容器,我在其中注册类型,如下所示:

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

摘星┃星的人 2024-08-30 02:30:33

好吧,我想通了。注册期间保持名称相同是正确的(“PopulationRate”和“BusinessLicenseRate”)。我所要做的就是向每个服务的构造函数中的 ItaxAuthorityRateService 参数添加一个属性,如下所示:

Service1 构造函数参数:

[Dependency( "BusinessLicenseRate" )]
ITaxAuthorityRateService rateService

Service2 构造函数参数:

[Dependency( "PopulationRate" )]
ITaxAuthorityRateService rateService

然后每个服务都会收到正确的 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:

[Dependency( "BusinessLicenseRate" )]
ITaxAuthorityRateService rateService

Service2 constructor parameter:

[Dependency( "PopulationRate" )]
ITaxAuthorityRateService rateService

And then each service received the correct ITaxAuthorityRateService instance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文