首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将经过修饰的命令处理程序类绑定到Ninject

如何将经过修饰的命令处理程序类绑定到Ninject
EN

Stack Overflow用户
提问于 2015-03-31 13:36:37
回答 1查看 644关注 0票数 0

我有一个命令处理程序接口类型,

代码语言:javascript
运行
复制
public interface ICommandHandler<in TCommand>
{
    void Handle(TCommand command);
}

实现的命令处理程序是由命令分派对象执行的。

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
           Kernel.Bind(scanner =>     
           scanner.FromAssembliesMatching("*")
           .IncludingNonePublicTypes()
           .SelectAllClasses()
           .InheritedFrom(typeof(ICommandHandler<>))
           .BindSingleInterface());

这个很管用。

但是我需要命令处理程序装饰器,例如验证:

代码语言:javascript
运行
复制
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对象执行的。

EN

回答 1

Stack Overflow用户

发布于 2015-03-31 16:53:45

Ninject不支持装饰器配置。

但是,您可以使用上下文绑定来实现装饰:

代码语言:javascript
运行
复制
Bind(typeof(ICommandHandler<>))
  .To(typeof(PostCommitCommandHandlerDecorator<>));

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

而不是.When(..)重载,.WhenInjectedInto(typeof(PostCommitCOmmandHandlerDecorator<>))可能也能工作,但我怀疑它不会工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29370021

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档