2011-10-21 16 views
8

Làm thế nào để làm điều đó trong mã được giải thích ở đây: Unity Register two interfaces as one singletonLàm thế nào tôi có thể đăng ký một singleton cho các giao diện khác nhau trong sự thống nhất, cấu hình XML?

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

bool singleton = ReferenceEquals(_container.Resolve<IEventService>(), _container.Resolve<IEventServiceInformation>()); 

Làm thế nào để làm điều đó trong cấu hình XML?

Trả lời

12

Cá nhân tôi muốn giải thích rõ ràng không gian tên và lắp ráp trong bí danh. Vì vậy, 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> 

mã:

IUnityContainer container = new UnityContainer().LoadConfiguration(); 
+0

Và được cả hai trường hợp của Event_Class gonna được giống nhau không? – lukebuehler

+2

Có. ReferenceEquals của bạn sẽ hoạt động. – ErnieL

0

tôi đã không làm việc với các tập tin cấu hình cho sự hiệp nhất, nhưng theo các tài liệu đó là

<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> 
+2

bạn bỏ lỡ <đời type = "singleton" /> – ErnieL

Các vấn đề liên quan