3

我有这堂课:

public class MessageService
{
    private readonly IMessageSender messageSender;

    public MessageService(IMessageSender messageSender)
    {
        this.messageSender = messageSender;
    }
}

如何注册autofac以在构造函数中传递参数:

var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
builder.RegisterType<MandrillMessageSender>().As<IMessageSender>();

builder.RegisterType<MessageService>(new MandrillMessageSender()); // NOTE THIS STRING IS NOT WORKING

所以结果应该是这样的,当我在控制器构造函数中传递参数时,应该使用插入的 MandrillMessageSerder 创建 messageService 对象。

public Home(MessageService messageService)
4

1 回答 1

2

您需要在RegisterType调用之前完成所有调用 builder.Build()

var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<MandrillMessageSender>().As<IMessageSender>();
builder.RegisterType<MessageService>();

var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

MessageService请注意,如果您只有一个接口实现,则不需要在注册中传递任何内容IMessageSender(Autofac 会发现您需要该接口MandrillMessageSender

于 2013-02-17T13:49:02.190 回答