2015-03-31 48 views
0

具有命令處理程序接口類型,我如何裝飾命令處理程序類綁定Ninject

public interface ICommandHandler<in TCommand> 
{ 
    void Handle(TCommand command); 
} 

實施命令處理程序執行由命令調度對象。

public class CommandDispacher : ICommandDispatcher 
{ 
    private readonly IServiceLocator serviceLocator; 

    public CommandDispacher(IServiceLocator serviceLocator) 
    { 
     this.serviceLocator = serviceLocator; 
    } 

    public void Dispatch<TCommand>(ICommand command) 
    { 
     var commandType = typeof(ICommandHandler<>).MakeGenericType(command.GetType()); 
     var handler = serviceLocator.Resolve(commandType); 

     ((dynamic)handler).Handle((dynamic)command); 
    } 
} 

我被ninject結合命令處理程序類是這樣的:

  Kernel.Bind(scanner =>  
      scanner.FromAssembliesMatching("*") 
      .IncludingNonePublicTypes() 
      .SelectAllClasses() 
      .InheritedFrom(typeof(ICommandHandler<>)) 
      .BindSingleInterface()); 

這工作。

但我需要命令處理程序的裝飾,例如驗證:

public class PostCommitCommandHandlerDecorator<T> : ICommandHandler<T> where T:ICommand 
{ 
    private readonly ICommandHandler<T> decorated; 
    private readonly PostCommitRegistratorImpl registrator; 

    public PostCommitCommandHandlerDecorator(ICommandHandler<T> decorated, PostCommitRegistratorImpl registrator) 
    { 
     this.decorated = decorated; 
     this.registrator = registrator; 
    } 

    public void Handle(T command) 
    { 
     try 
     { 
      decorated.Handle(command); 

      registrator.ExecuteActions(); 
     } 
     catch (Exception) 
     { 
      registrator.Reset(); 
     } 
    } 
} 

我如何裝飾我的命令處理程序類與此類似裝飾? 我應該將它綁定到Ninject內核嗎?因爲我的命令是由ICommandDispatches對象執行的。

回答

1

開箱即用Ninject不支持裝飾器配置。

但是,您可以使用contextual bindings實現裝飾:

Bind(typeof(ICommandHandler<>)) 
    .To(typeof(PostCommitCommandHandlerDecorator<>)); 

Bind(typeof(ICommandHandler<>)) 
    .To(typeof(CommandHandler<>)) 
    .When(request => 
    request.Target.Type.GetGenericTypeDefinition() 
    == typeof(PostCommitCommandHandlerDecorator<>)); 

取而代之的是.When(..)超載.WhenInjectedInto(typeof(PostCommitCOmmandHandlerDecorator<>))的可能工作爲好,但我懷疑它不會。