【发布时间】:2017-03-16 15:06:42
【问题描述】:
我使用的是 .NET Core(注意:不是 Web 环境)。我需要集成 MediatR 和 Autofac。
wiki has a guide 和 StructureMap 示例。另外,我已经简化了Autofac sample。没有提到生命周期范围,但是在a separate project 中,我找到了有用的 cmets 并将它们转换为 Autofac。有很多代码示例漂浮在各处,每个示例都不相同。
到目前为止我得到了什么:
// enables contravariant Resolve() for interfaces with single contravariant ("in") arg
builder
.RegisterSource(new ContravariantRegistrationSource());
// mediator itself
builder
.RegisterType<Mediator>()
.As<IMediator>()
.InstancePerLifetimeScope();
// request handlers
builder
.Register<SingleInstanceFactory>(context => {
var ctx = context.Resolve<IComponentContext>(); // unsure why needed, but it works
return t => { object o; return ctx.TryResolve(t, out o) ? o : null; };
})
.InstancePerLifetimeScope();
// notification handlers
builder
.Register<MultiInstanceFactory>(context => {
var ctx = context.Resolve<IComponentContext>(); // unsure why needed, but it works
return t => (IEnumerable<object>)ctx.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
})
.InstancePerLifetimeScope();
然后注册我的自定义东西:
- 处理程序是瞬态的,即
InstancePerDependency() - 根据请求的前/后处理器,即
InstancePerLifetimeScope() - 行为为瞬态,即
InstancePerDependency()
例如
builder.RegisterType<EditCommandHandler>().AsImplementedInterfaces().InstancePerDependency();
但是,在我见过的大多数代码示例中,尤其是对于 StructureMap,还有大量其他注册(例如 IRequestHandler<,>、IRequestHandler<>、IAsyncRequestHandler<,>、IAsyncRequestHandler<>、ICancellableAsyncRequestHandler<,>、ICancellableAsyncRequestHandler<> 、INotificationHandler<>、IAsyncNotificationHandler<>、ICancellableAsyncNotificationHandler<>) 和ASP.NET Core container's 集成也非常复杂。我没有做过类似的事情。
如果你有这个在生产中工作,你的配置与我的相比如何?谢谢!
【问题讨论】:
标签: .net .net-core autofac mediatr