c# - 了解 Mediatr 的 Autofac 配置

标签 c# autofac mediatr

我正在尝试配置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 from ctx, given that ctx is already an IComponentContext.

您不能使用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, 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.

ctxRegister提供方法仅为注册过程而构建,并将在注册过程结束时被处置。这就是为什么你必须解决另一个 IComponentContext得到一个在整个生命周期范围内都活着的东西。

关于c# - 了解 Mediatr 的 Autofac 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59082159/

相关文章:

c# - HTTP 请求处于挂起状态,直到执行 MediatR 通知

c# - 构建前和构建后事件参数

c# - 在日志条目中表示持续时间的最佳方式

c# - Windows 应用商店应用程序中的 SQLite 异常

c# - 计时器流逝的资源全局化

c# - 在 Owin Startup 上解析 InstancePerLifetimeScope 中的 Autofac 服务

ioc-container - AutoFac - 使用已知服务实例化未注册的服务

c# - Autofac 日志记录模块和 ASP.Net Web 表单中的解析参数

c# - MediatR 和 SimpleInjector 的依赖范围问题

domain-driven-design - 是否可以在没有依赖注入(inject) (DDD) 的情况下在聚合(域层)中实现 MediatR?