Applying generic decorators conditionally in Autof

2019-07-21 12:03发布

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条回答
地球回转人心会变
2楼-- · 2019-07-21 12:27

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.

查看更多
登录 后发表回答