【问题标题】:Unity resolving concrete classes to generic interfaces when availableUnity 在可用时将具体类解析为通用接口
【发布时间】:2011-10-17 15:54:21
【问题描述】:

我可以将通用接口解析为通用类,例如通用通用存储库模式。

IRepository<objectA> resolves to Repository<objectA>
IRepository<objectB> resolves to Repository<objectB>

但是对于objectC,我需要一个具体的存储库,即扩展Repository&lt;objectC&gt;ObjectCRepository。如果我注册,IRepository&lt;objectC&gt; 不会有两个不同的注册并且一切都失败了吗?

【问题讨论】:

  • 可以的。需要查看您的代码。
  • 抱歉没有得到代码,因为我想知道这是否可以先完成。但是我在统一配置方面遇到了其他问题stackoverflow.com/questions/7809204/…

标签: generics unity-container


【解决方案1】:

会有两个注册,但不会冲突。 Unity 足够聪明,可以更喜欢完全定义的封闭泛型而不是开放泛型。例如,这很好用:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="ILog_Interface" type="Common.ILog`1, Common2"/>
    <alias alias="Logger_Class" type="Common.Logger`1, Common2"/>
    <alias alias="DemoServiceLog_Interface" type="Common.ILog`1[[Services.Demo.DemoService, Services.Demo]], Common2"/>
    <alias alias="DemoServiceLog_Class" type="Common.ServiceLogger`1[[Services.Demo.DemoService, Services.Demo]], Common2"/>

        <container name="DemoService">
          <register type="ILog_Interface" mapTo="Logger_Class"/>
          <register type="DemoServiceLog_Interface" mapTo="DemoServiceLog_Class"/>
        </container>
</unity>

【讨论】:

  • 很高兴知道,所以我可以注册具体的 UserRepository : Repository 到 IRepository 以及通用 Repository 到 IRepository,它应该可以解决。跨度>
猜你喜欢
  • 2017-06-18
  • 2020-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
相关资源
最近更新 更多