如何在统一的XML配置中将一个单例注册到不同的接口?

luk*_*ler 8 .net c# unity-container

下面解释如何在代码中执行此操作: Unity将两个接口注册为一个单例

_container.RegisterType<EventService>(new ContainerControlledLifetimeManager());
_container.RegisterType<IEventService, EventService>();
_container.RegisterType<IEventServiceInformation, EventService>();

bool singleton = ReferenceEquals(_container.Resolve<IEventService>(),   _container.Resolve<IEventServiceInformation>());
Run Code Online (Sandbox Code Playgroud)

如何在XML配置中执行此操作?

Ern*_*ieL 12

我个人喜欢在别名中拼出名称空间和程序集.所以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>
Run Code Online (Sandbox Code Playgroud)

码:

IUnityContainer container = new UnityContainer().LoadConfiguration();
Run Code Online (Sandbox Code Playgroud)