我们都知道在MVC下使用Autofac很容易设置依赖解析器但是我们最近将在控制台应用程序中使用DI / IoC,而事情并非如此简单。
代码优先:
var builder = new ContainerBuilder();
// sample registrations not important
builder.RegisterType<MessageCommandHandler>().Named<IHandler<Message>>("handler");
builder.RegisterDecorator<IHandler<Message>>(
(c, inner) => new TransactionalHandlerDecorator<Message>(inner),
fromKey: "handler",
toKey: "transactional");
var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
var scopedHandler = scope.Resolve<IHandler<Message>>();
scopedHandler.Handle(new Message());
}
正如您所知,我手动创建了生命周期范围,但我想知道在示例控制台应用中使用示波器的正确方法是什么?我应该以这种方式使用它:
var builder = new ContainerBuilder();
// sample registrations not important
builder.RegisterType<MessageCommandHandler>().Named<IHandler<Message>>("handler");
builder.RegisterDecorator<IHandler<Message>>(
(c, inner) => new TransactionalHandlerDecorator<Message>(inner),
fromKey: "handler",
toKey: "transactional");
var container = builder.Build();
var handler = container.Resolve<IHandler<Message>>();
handler.Handle(new Message());
有什么区别?建议在控制台应用程序中使用生命周期范围的方法是哪一种?