我如何注册一个单例到不同的接口在统一,XML配置
本文关键字:接口 配置 XML 单例 何注册 注册 一个 | 更新日期: 2023-09-27 18:11:48
如何在代码中做到这一点解释如下:Unity注册两个接口为一个单例
_container.RegisterType<EventService>(new ContainerControlledLifetimeManager());
_container.RegisterType<IEventService, EventService>();
_container.RegisterType<IEventServiceInformation, EventService>();
bool singleton = ReferenceEquals(_container.Resolve<IEventService>(), _container.Resolve<IEventServiceInformation>());
如何在XML配置?
我个人喜欢在别名中拼出名称空间和程序集。因此,xml:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="Event_Interface" type="Mynamespace.IEventService, MyAssembly"/>
<alias alias="EventService_Interface" type="Mynamespace.IEventServiceInformation, MyAssembly"/>
<alias alias="Event_Class" type="Mynamespace.EventService, MyAssembly"/>
<container>
<register type="Event_Interface" mapTo="Event_Class">
<lifetime type="singleton"/>
</register>
<register type="EventService_Interface" mapTo="Event_Class">
<lifetime type="singleton"/>
</register>
</container>
</unity>
代码:IUnityContainer container = new UnityContainer().LoadConfiguration();
有趣的是,公认的解决方案并不适合我…它最终会创建两个单例,呵呵,每个接口一个。对我来说,诀窍是首先将类型注册为具有singleton生命周期,然后添加没有任何生命周期的实际映射。这样的:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="Event_Interface" type="Mynamespace.IEventService, MyAssembly"/>
<alias alias="EventService_Interface" type="Mynamespace.IEventServiceInformation, MyAssembly"/>
<alias alias="Event_Class" type="Mynamespace.EventService, MyAssembly"/>
<container>
<register type="Event_Class">
<lifetime type="singleton"/>
</register>
<register type="Event_Interface" mapTo="Event_Class"/>
<register type="EventService_Interface" mapTo="Event_Class"/>
</container>
我还没有使用unity的配置文件,但根据文档,它是
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<namespace name="MyApp.Implementations" />
<assembly name="MyApp" />
<container>
<register type="IEventService" mapTo="EventService" />
<register type="IEventServiceInformation" mapTo="EventService" />
</container>
</unity>