我正在尝试配置Mediatr与 Autofac。 documentation显示了如何配置它,但我不明白 ServiceFactory 注册是如何工作的。
注册方式如下:
builder.Register<ServiceFactory>(ctx =>
{
var c = ctx.Resolve<IComponentContext>();
return t => c.Resolve(t);
});
ServiceFactory 是一个委托(delegate):
/// <summary>
/// Factory method used to resolve all services. For multiple instances, it will resolve against <see cref="IEnumerable{T}" />
/// </summary>
/// <param name="serviceType">Type of service to resolve</param>
/// <returns>An instance of type <paramref name="serviceType" /></returns>
public delegate object ServiceFactory(Type serviceType);
我的理解是,在解析ServiceFactory
时,Autofac会解析匿名函数:
t=>c.Resolve(t)
但我不明白为什么 IComponentContext
是从 ctx
解析的,因为 ctx 已经是 IComponentContext
了。
那么以这种方式注册会有什么不同:
builder.Register<ServiceFactory>(ctx =>
{
return t => ctx.Resolve(t);
});
最佳答案
My understanding is that when resolving ServiceFactory, Autofac will resolve the anonymous function
你是对的。
but I don't understand why
IComponentContext
is resolved fromctx
, given thatctx
is already anIComponentContext
.
您不能使用ctx
因为当调用委托(delegate)时,此上下文将被释放。如果你这样做
builder.Register<ServiceFactory>(ctx =>
{
return t => ctx.Resolve(t);
});
您将拥有ObjectDisposedException
当您调用ServiceFactory
时代表。
System.ObjectDisposedException
: This resolve operation has already ended. When registering components using lambdas, theIComponentContext
'ctx' parameter to the lambda cannot be stored. Instead, either resolveIComponentContext
again from 'ctx', or resolve aFunc<>
based factory to create subsequent components from.
ctx
由Register
提供方法仅为注册过程而构建,并将在注册过程结束时被处置。这就是为什么你必须解决另一个 IComponentContext
得到一个在整个生命周期范围内都活着的东西。
关于c# - 了解 Mediatr 的 Autofac 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59082159/