我正在使用Autofac实现命令处理程序模式,并正在使用其装饰器功能来处理诸如日志记录,身份验证等交叉问题。
我也有一些依赖关系,我只希望将其范围限制在请求/响应管道的生命周期内。
我在下面有一个示例实现:
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);
}
}
如您所见,我将pipleine包裹在一个名为
pipeline
的作用域中,这意味着每次我将范围为LifetimeScopeTester
的pipeline
解析为decoratedHandler
时,都会得到相同的实例。我以为我可以取代
using(var scope = container.BeginLifetimeScope("pipline")) {
var pingHandler = scope.Resolve<IHandle<PingRequest, PingResponse>>();
pingHandler.Handle(new PingRequest());
}
与
var pingHandler = scope.Resolve<IHandle<PingRequest, PingResponse>>();
pingHandler.Handle(new PingRequest());
通过创建另一个完成相同功能的装饰器。
我的第一个直觉是:
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;
}
}
但是
_decoratedHandlerFactory()
会在注入时已经解决,因此将无法正常工作。所以我尝试了:
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;
}
}
但是,此过程无限重复,因为调用
LifetimeScopeHandler
尝试再次使用装饰器包装内部处理程序。这是我正在努力实现的目标。
我在https://dotnetfiddle.net/hwujNI处创建了一个dotnetfiddle来演示此问题。
最佳答案
当Handle
类的LifetimeScopeHandler
方法调用decoratedHandlerFactory
委托时,它要求Autofac解析为IHandle<TRequest, TResponse>
的LifetimeScopeHandler
。这就是为什么您有StackOverflowException
的原因。我们可以将您的情况简化为以下代码示例:
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();
}
}
即使只有一个
Foo
实例,您也会有一个StackOverflowException
为了解决此问题,您必须向Autofac指示
decoratedHandlerFactory
的LifetimeScopeHandler
委托不应该是LifetimeScopeHandler
的委托。您可以使用
WithParameter
指示最后一个装饰器使用特定的参数:builder.RegisterGenericDecorator(
typeof(LifetimeScopeHandler<,>),
typeof(IHandle<,>),
"FirstDecoratorHandler"
)
.WithParameter((pi, c) => pi.Name == "decoratedHandlerFactory",
(pi, c) => c.ResolveKeyed("FirstDecoratorHandler", pi.ParameterType))
.As(typeof(IHandle<,>));
使用此配置,输出将是
LifetimeScopeHandler
FirstDecoratorHandler-LifetimeScopeTester [52243212]
SecondDecoratorHandler-LifetimeScopeTester [52243212]
PingHandler
顺便说一句,您希望
LifetimeScopeHandler
是一种特殊的装饰器,它将在特殊范围内创建内部IHandler<,>
。您可以通过要求
LifetimeScopeHandler
为您创建正确的作用域并解决先前的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;
}
}
}
此实现将要求
LifetimeScopeHandler
知道链上的第一个装饰器,我们可以通过在其构造器上发送名称来绕过它。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;
}
}
}
您将必须像这样注册:
builder.RegisterGenericDecorator(
typeof(LifetimeScopeHandler<,>),
typeof(IHandle<,>),
"FirstDecoratorHandler"
)
.WithParameter("previousHandlerName", "FirstDecoratorHandler")
.As(typeof(IHandle<,>));
我们也可以不使用
RegisterGenericDecorator
方法来绕过所有内容。如果我们这样注册
LifetimeScopeHandler
: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<,>));
现在
LifetimeScopeHandler
看起来像所有装饰器: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;
}
}
顺便说一句,如果您在一个范围内使用多个
IHandler<,>
并且需要一个单一的pipline
范围,则此解决方案可能会出现问题。要解决此问题,您可以看到以下dotnetfiddle:https://dotnetfiddle.net/rQgy2X,但是在我看来,它过于复杂,您可能不需要它。关于c# - Autofac终身范围装饰器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31230305/