2011-06-03 30 views
2

我想使用unity來處理通過容器註冊的多態事件聚合/處理。考慮衝突使Unity解決實現

處理程序使用「in」修飾符聲明一個通用參數,因爲它僅用作輸入參數。所以參數是逆變的。

考慮以下示例。

interface IHandler<in T> { void Handle(T message); } 

interface IMsg { string Message { get; } } 

class MsgA : IMsg { ... } 

class MsgB : IMsg { ... } 

class MsgAHandler : IHandler<MsgA> { 
    public void Handle(MsgA msg) { ... } 
} 

class MsgBHandler : IHandler<MsgB> { 
    public void Handle(MsgB msg) { ... } 
} 

class MsgHandler : IHandler<IMsg> { 
    public void Handle(IMsg msg) { ... } 
} 

class ObjectHandler : IHandler<object> { 
    public void Handle(object msg) { ... } 
} 

class Events { 
    public void Publish<T>(T message) { 
    // Actually this code is more complex for Unity, because it first tries to 
    // resolve the default registered component using .Resolve(), 
    // then use .ResolveAll() to resolve all named components 
    foreach (var handler in this.container.ResolveAll<IHandle<T>>()) { 
     handler.Handle(message); 
    } 
    } 
} 

我的期望是以下內容:

  • 如果我收到MsgA,我應該把它分派到MsgAHandlerMsgHandlerObjectHandler
  • 如果我收到IMsg,我應該將其發送到MsgHandlerObjectHandler
  • ObjectHandler應接收所有消息。

默認情況下,Castle Windsor在沒有任何特定配置(用v2.5.1測試)的情況下正確處理這種情況。

Unity是否公開了一種提高分辨率的方法,並允許Resolve<IHandle<MsgA>>()也匹配實現IHandle<IMsg>IHandle<object>的任何類型?

我查找過使用UnityExtensions(匹配規則,策略等)但沒有成功的示例。

有人能指引我使用正確的機制來實現這樣的場景嗎?

回答

1

你知道:

container.RegisterType(typeof(IHandle<>), typeof(MsgAHandler<>)) 

但你可能需要改變你的一些代碼爲正常工作。像:

public interface IHandler<in THandler> where THandler : class, IMsg 
{ void Handle(THandler message); }