2015-08-21 76 views
2

我運行的是有線起來使用the almighty SimpleInjector3在.NET4.0的Web應用程序的安裝程序。我正在使用Command-/QueryHandler architecture described here,並且在爲命令處理程序配置依賴項時遇到問題。註冊開放式泛型類型作爲後備使用簡單的注射器

示例代碼

這裏是階級結構的崩潰:

interface ICommandHandler<T> 
{ 
    void Handle(T command); 
} 

enum LoggingState { Success, Failed } 

interface ICommandLogger<T> 
{ 
    void Log(LoggingState state, T command); 
} 

class NullCommandLogger<T> : ICommandLogger<T> 
{ 
    void Log(LoggingState state, T command) 
    { 
     // Intentionally left blank 
    } 
} 

裝飾:

/// <summary> 
/// The logging command handler that gets wrapped around every 
/// command handlers. 
/// </summary> 
class LoggingCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand> 
{ 
    private readonly ICommandHandler<TCommand> decorated; 
    private readonly ICommandLogger<TCommand> logger; 

    public LoggingCommandHandlerDecorator(
     ICommandHandler<TCommand> decorated, 
     ICommandLogger<TCommand> logger) 
    { 
     this.decorated = decorated; 
     this.logger = logger; 
    } 

    public void Handle(TCommand command) 
    { 
     try 
     { 
      this.decorated.Handle(command); 
     } 
     catch (Exception) 
     { 
      this.logger.Log(LoggingState.Failed, command); 
      throw; 
     } 

     this.logger.Log(LoggingState.Success, command); 
    } 
} 

在我CompositionRoot我配置它是這樣的:

var assembly = /* Get the assembly where the handlers are located */ 

// Register all explicitly defined loggers 
container.Register(typeof(ICommandLogger<>), assembly); 

// Register null objects for everything else 
container.RegisterConditional(
    typeof(ICommandLogger<>), 
    typeof(NullCommandLogger<>), 
    ctx => !ctx.Handled); 

// Wrap all command handlers with the logging 
container.RegisterDecorator(
    typeof(ICommandHandler<>), 
    typeof(LoggingCommandHandlerDecorator<>)); 

這非常適用於非通用記錄器像這樣的:

​​

的問題

現在我有一組實現一個標記接口命令,這樣我可以用一個單記錄所有的 - 他們,但這樣會不會被SimpleInjector回升:

class NotWorkingLogger<T> : ICommandLogger<T> 
    where T : IMarkerInterface { /* ... */ } 

我知道,這不應該是一個問題,方差,但我已經使用variance extensions只是可以肯定的嘗試,但都無濟於事。

有沒有辦法配置這種情況?

回答

1

你只需要添加的登記NotWorkingLogger<T>明確如下:

container.Register(typeof(ICommandLogger<>), assembly); 

// It's added between the two other registrations 
container.RegisterConditional(
    typeof(ICommandLogger<>), 
    typeof(NotWorkingLogger<>), 
    ctx => !ctx.Handled); 

container.RegisterConditional(
    typeof(ICommandLogger<>), 
    typeof(NullCommandLogger<>), 
    ctx => !ctx.Handled); 
+0

啊,太簡單了:-D。謝謝! – mfeineis

相關問題