Autofac Lifetime Scope Decorator

2020-07-27 05:51发布

问题:

I am implementing a command handler pattern using Autofac and am using it's decorator facility handle cross cutting concerns such as logging, authentication etc.

I also have dependencies that I only want scoped to the lifetime of the request / response pipeline.

I have an example implementation below:

public class Program
{
    public static void Main()
    {
        var builder = new ContainerBuilder();
        builder.RegisterAssemblyModules(typeof(HandlerModule).Assembly);
        builder.RegisterType<LifetimeScopeTester>().AsSelf()
            .InstancePerMatchingLifetimeScope("pipline");

        var container = builder.Build();

        using(var scope = container.BeginLifetimeScope("pipline")) {
            var pingHandler = scope.Resolve<IHandle<PingRequest, PingResponse>>();
            pingHandler.Handle(new PingRequest());
        }
    }
}

public class HandlerModule : Autofac.Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterAssemblyTypes(ThisAssembly)
            .As(type => type.GetInterfaces()
            .Where(interfaceType => interfaceType.IsClosedTypeOf(typeof (IHandle<,>)))
            .Select(interfaceType => new KeyedService("IHandle", interfaceType)));

        builder.RegisterGenericDecorator(
            typeof(SecondDecoratorHandler<,>),
            typeof(IHandle<,>),
            "IHandle"
        )
        .Keyed("SecondDecoratorHandler", typeof(IHandle<,>));

        builder.RegisterGenericDecorator(
            typeof(FirstDecoratorHandler<,>),
            typeof(IHandle<,>),
            "SecondDecoratorHandler"
        );
    }
}

public class LifetimeScopeTester {}

public interface IHandle<in TRequest, out TResponse> 
    where TRequest : class, IRequest<TResponse>
{
   TResponse Handle(TRequest request);
}

public interface IRequest<TResponse> {

}

public class PingRequest : IRequest<PingResponse> {

}

public class PingResponse {

}

public class PingHandler : IHandle<PingRequest, PingResponse> {
    public PingResponse Handle(PingRequest request) {
        Console.WriteLine("PingHandler");
        return new PingResponse();
    }
}

public class FirstDecoratorHandler<TRequest, TResponse> : IHandle<TRequest, TResponse>
    where TRequest : class, IRequest<TResponse>
{
    private readonly IHandle<TRequest, TResponse> _decoratedHandler;
    private readonly LifetimeScopeTester _lifetimeScopeTester;

    public FirstDecoratorHandler(IHandle<TRequest, TResponse> decoratedHandler,
        LifetimeScopeTester lifetimeScopeTester)
    {
        _decoratedHandler = decoratedHandler;
        _lifetimeScopeTester = lifetimeScopeTester;
    }

    public TResponse Handle(TRequest request)
    {
        Console.WriteLine("FirstDecoratorHandler - LifetimeScopeTester[{0}]",
            _lifetimeScopeTester.GetHashCode());
        return _decoratedHandler.Handle(request);
    }
}

public class SecondDecoratorHandler<TRequest, TResponse> : IHandle<TRequest, TResponse> 
    where TRequest : class, IRequest<TResponse>
{
    private readonly IHandle<TRequest, TResponse> _decoratedHandler;
    private readonly LifetimeScopeTester _lifetimeScopeTester;

    public SecondDecoratorHandler(IHandle<TRequest, TResponse> decoratedHandler, LifetimeScopeTester lifetimeScopeTester)
    {
        _decoratedHandler = decoratedHandler;
        _lifetimeScopeTester = lifetimeScopeTester;
    }

    public TResponse Handle(TRequest request)
    {
        Console.WriteLine("SecondDecoratorHandler - LifetimeScopeTester[{0}]", _lifetimeScopeTester.GetHashCode());
        return _decoratedHandler.Handle(request);
    }
}

As you can see, I wrap the pipleine in a scope named pipeline which means that everytime I resolve LifetimeScopeTester which is scope to pipeline, I get the same instance.

I as thinking that I might be able to replace

using(var scope = container.BeginLifetimeScope("pipline")) {
    var pingHandler = scope.Resolve<IHandle<PingRequest, PingResponse>>();
    pingHandler.Handle(new PingRequest());
}

with

var pingHandler = scope.Resolve<IHandle<PingRequest, PingResponse>>();
pingHandler.Handle(new PingRequest());

by creating another decorator that does that same thing.

My first instinct was:

public class LifetimeScopeDecoratorHandler<TRequest, TResponse> : IHandle<TRequest, TResponse> 
    where TRequest : class, IRequest<TResponse>
{
    private readonly ILifetimeScope _scope;
    private readonly IHandle<TRequest, TResponse> _decoratedHandler;

    public LifetimeScopeDecoratorHandlerAttempt1(ILifetimeScope scope, 
        IHandle<TRequest, TResponse> decoratedHandler)
    {
        _scope = scope;
        _decoratedHandler = decoratedHandler;
    }

    public TResponse Handle(TRequest request)
    {
        Console.WriteLine("LifetimeScopeDecoratorHandler");

        TResponse response;

        using (_scope.BeginLifetimeScope("pipeline"))
        {
            response = _decoratedHandler.Handle(request);
        }

        return response;
    }
}

But the decoratedHandler would have already been resolved by the time it's injected so that won't work.

So I tried:

public class LifetimeScopeHandler<TRequest, TResponse> : IHandle<TRequest, TResponse> 
    where TRequest : class, IRequest<TResponse>
{
    private readonly ILifetimeScope _scope;
    private readonly Func<IHandle<TRequest, TResponse>> _decoratedHandlerFactory;

    public LifetimeScopeHandler(ILifetimeScope scope, 
        Func<IHandle<TRequest, TResponse>> decoratedHandlerFactory)
    {
        _scope = scope;
        _decoratedHandlerFactory = decoratedHandlerFactory;
    }

    public TResponse Handle(TRequest request)
    {
        Console.WriteLine("LifetimeScopeDecoratorHandler");

        TResponse response;

        using (_scope.BeginLifetimeScope("pipeline"))
        {
            var decoratedHandler = _decoratedHandlerFactory();
            response = decoratedHandler.Handle(request);
        }

        return response;
    }
}

However this repeated infinitely as calling _decoratedHandlerFactory() tries to wrap the inner handler with a LifetimeScopeHandler decorator again.

Is what I'm trying to achieve possible.

I have created a dotnetfiddle at https://dotnetfiddle.net/hwujNI demonstrating the issue.

回答1:

When the Handle method of LifetimeScopeHandler class invoke the decoratedHandlerFactory delegate, it asks Autofac to resolve a IHandle<TRequest, TResponse> which is a LifetimeScopeHandler. That's why you have a StackOverflowException. We can simplify your case to this code sample :

public class Foo
{
    public Foo(Func<Foo> fooFactory)
    {
        this._fooFactory = fooFactory;
    }
    private readonly Func<Foo> _fooFactory;

    public void Do()
    {
        Foo f = this._fooFactory();
        f.Do();
    }
}

Even if there is a single instance of Foo you will have a StackOverflowException

In order to resolve this issue, you have to indicate Autofac that the decoratedHandlerFactory delegate of LifetimeScopeHandler should not be a delegate of LifetimeScopeHandler.

You can use the WithParameter to indicate the last decorator to use a specific parameter :

builder.RegisterGenericDecorator(
    typeof(LifetimeScopeHandler<,>),
    typeof(IHandle<,>),
    "FirstDecoratorHandler"
)
.WithParameter((pi, c) => pi.Name == "decoratedHandlerFactory",
               (pi, c) => c.ResolveKeyed("FirstDecoratorHandler", pi.ParameterType))
.As(typeof(IHandle<,>));

With this configuration, the output will be

LifetimeScopeHandler
FirstDecoratorHandler - LifetimeScopeTester[52243212]
SecondDecoratorHandler - LifetimeScopeTester[52243212]
PingHandler

By the way, you want LifetimeScopeHandler to be a special kind of decorator that will create the inner IHandler<,> in a special scope.

You can do this by asking the LifetimeScopeHandler to create the correct scope for you and resolve the previous Ihandler.

public class LifetimeScopeHandler<TRequest, TResponse> 
    : IHandle<TRequest, TResponse> where TRequest : class, IRequest<TResponse>
{
    private readonly ILifetimeScope _scope;

    public LifetimeScopeHandler(ILifetimeScope scope)
    {
        this._scope = scope;
    }

    public TResponse Handle(TRequest request)
    {
        Console.WriteLine("LifetimeScopeDecoratorHandler");

        using (ILifetimeScope s = this._scope.BeginLifetimeScope("pipline"))
        {
            var decoratedHandler = 
                s.ResolveKeyed<IHandle<TRequest, TResponse>>("FirstDecoratorHandler");
            TResponse response = decoratedHandler.Handle(request);
            return response;
        }
    }
}

This implementation will require that LifetimeScopeHandler knows the first decorator on the chain, we can bypass that by sending the name on its constructor.

public class LifetimeScopeHandler<TRequest, TResponse> 
    : IHandle<TRequest, TResponse> where TRequest : class, IRequest<TResponse>
{
    private readonly ILifetimeScope _scope;
    private readonly String _previousHandlerName; 

    public LifetimeScopeHandler(ILifetimeScope scope, String previousHandlerName)
    {
        this._scope = scope;
        this._previousHandlerName = previousHandlerName; 
    }

    public TResponse Handle(TRequest request)
    {
        Console.WriteLine("LifetimeScopeDecoratorHandler");

        using (ILifetimeScope s = this._scope.BeginLifetimeScope("pipline"))
        {
            var decoratedHandler = 
                s.ResolveKeyed<IHandle<TRequest, TResponse>>(previousHandlerName);
            TResponse response = decoratedHandler.Handle(request);
            return response;
        }
    }
}

And you will have to register it like this :

builder.RegisterGenericDecorator(
         typeof(LifetimeScopeHandler<,>),
         typeof(IHandle<,>),
         "FirstDecoratorHandler"
       )
       .WithParameter("previousHandlerName", "FirstDecoratorHandler")
       .As(typeof(IHandle<,>));

We can also bypass everything by not using the RegisterGenericDecorator method.

If we register the LifetimeScopeHandler like this :

builder.RegisterGeneric(typeof(LifetimeScopeHandler<,>))
       .WithParameter((pi, c) => pi.Name == "decoratedHandler",
                      (pi, c) =>
                      {
                          ILifetimeScope scope = c.Resolve<ILifetimeScope>();
                          ILifetimeScope piplineScope = scope.BeginLifetimeScope("pipline");
                          var o = piplineScope.ResolveKeyed("FirstDecoratorHandler", pi.ParameterType);
                          scope.Disposer.AddInstanceForDisposal(piplineScope);
                          return o;
                      })
       .As(typeof(IHandle<,>));

And LifetimeScopeHandler can now look like all decorator :

public class LifetimeScopeHandler<TRequest, TResponse> 
  : IHandle<TRequest, TResponse> where TRequest : class, IRequest<TResponse>
{
    private readonly IHandle<TRequest, TResponse> _decoratedHandler;

    public LifetimeScopeHandler(IHandle<TRequest, TResponse> decoratedHandler)
    {
        this._decoratedHandler = decoratedHandler;
    }

    public TResponse Handle(TRequest request)
    {
        Console.WriteLine("LifetimeScopeDecoratorHandler");

        TResponse response = this._decoratedHandler.Handle(request);
        return response;
    }
}

By the way, this solution may have an issue if you use more than one IHandler<,> in a scope and you need to have a single pipline scope. To resolve this, you can see this dotnetfiddle : https://dotnetfiddle.net/rQgy2X but it seems to me over complicated and you may not need it.