Autofac Lifetime Scope Decorator

自作多情 提交于 2019-12-04 21:55:52

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.

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