【发布时间】:2019-11-28 05:16:58
【问题描述】:
我正在尝试使用 Autofac 配置 Mediatr。 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);
});
【问题讨论】: