Applying generic decorators conditionally in Autofac based on configuration values

半世苍凉 提交于 2019-12-11 03:39:58

问题


I have an application with an command/handler based architecture. I have the following interface:

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

There are many non-generic implementations of this interface. Those implementations are wrapped by generic decorators such as:

public class ProfilingCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
    private readonly ICommandHandler<TCommand> decoratee;

    public ProfilingCommandHandlerDecorator(ICommandHandler<TCommand> decoratee)
    {
        this.decoratee = decoratee;
    }

    public void Handle(TCommand command)
    {
        // do profiling here
        this.decoratee.Handle(command);
        // aaand here.
    }
}

Some of these decotators however should be applied conditionally based on the flag in the config file. I found this answer that refers to applying non-generic decorators conditionally; not about generic decorator. How can we achieve this with generic decorators in Autofac?


回答1:


This most like involves implementing your own IRegistrationSource. If you pull the code for Autofac and look at OpenGenericDecoratorRegistrationSource, that should get you on the right track.



来源:https://stackoverflow.com/questions/23472611/applying-generic-decorators-conditionally-in-autofac-based-on-configuration-valu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!