【问题标题】:Autofac and generic command patternAutofac 和通用命令模式
【发布时间】:2016-07-31 17:45:14
【问题描述】:

我正在尝试装饰我的命令处理程序,并且我正在尝试在我的处理器中解决它们。

我这样注册我的命令:

builder.RegisterAssemblyTypes(typeof(ICommandProcessor).Assembly)
    .AsClosedTypesOf(typeof(ICommandHandler<,>))
    .AsSelf().AsImplementedInterfaces().Named("implementor", typeof(ICommandHandler<,>));

builder.RegisterGenericDecorator(
    typeof(CatchValidationErrorsDecorator<,>),
    typeof(ICommandHandler<,>), fromKey: "implementor")
    .AsImplementedInterfaces();

问题是当我不使用命名扩展时,通用装饰器不起作用。 当我使用命名扩展时,我无法像这样解析我的组件:

var handerType = typeof (ICommandHandler<,>)
    .MakeGenericType(command.GetType(), typeof (TResult));
dynamic handler = _container.Resolve(handerType);

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: c# autofac command-pattern


    【解决方案1】:

    过去这让我非常头疼。最终为我完成的注册是:

    var assembly = typeof(ICommandProcessor).Assembly);
    
    builder.RegisterAssemblyTypes(assembly).As(type =>
        from interfaceType in type.GetInterfaces()
        where interfaceType.IsClosedTypeOf(typeof(ICommandHandler<,>))
        select new KeyedService("implementor", interfaceType));
    
    builder.RegisterGenericDecorator(
        typeof(CatchValidationErrorsDecorator<,>), 
        typeof(ICommandHandler<,>),
        fromKey: "implementor");
    

    【讨论】:

    • 感谢您的回复。那成功了!还有一个问题,如果我需要在命令中处理命令并且不希望在另一个命令中触发时修饰命令处理程序怎么办?
    • @Manaus 我不建议这样做。命令应该是一个原子操作,而 ICommandHandler 应该是一个整体抽象。您应该将重复的代码提取到注入到处理程序中的服务中。根据层次结构中的位置有条件地包装您的处理程序是困难且容易出错的,即使使用其他容器也是如此。
    猜你喜欢
    • 2010-12-02
    • 2012-09-05
    • 2011-04-22
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多