了解 Mediatr 的 Autofac 配置

Understanding Autofac configuration for Mediatr

我正在尝试配置 Mediatr with Autofac. The documentation 展示了如何配置它,但我不明白 ServiceFactory 注册是如何工作的。

报名情况如下:

builder.Register<ServiceFactory>(ctx =>
{
   var c = ctx.Resolve<IComponentContext>();
   return t => c.Resolve(t);
});

而 ServiceFactory 是一个委托:

/// <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 from ctx, given that ctx is already an IComponentContext.

您不能使用 ctx,因为在调用委托时将释放此上下文。如果你这样做

builder.Register<ServiceFactory>(ctx =>
{
    return t => ctx.Resolve(t);
});

当您调用 ServiceFactory 委托时,您将拥有一个 ObjectDisposedException

System.ObjectDisposedException: This resolve operation has already ended. When registering components using lambdas, the IComponentContext 'ctx' parameter to the lambda cannot be stored. Instead, either resolve IComponentContext again from 'ctx', or resolve a Func<> based factory to create subsequent components from.

Register方法提供的ctx仅用于注册过程,将在注册过程结束时处理。这就是为什么你必须解决另一个 IComponentContext 以获得一个在整个生命周期范围内都有效的原因。