AutoFac Controller没有默认构造函数

时间:2014-10-02 06:35:25

标签: c# asp.net-web-api autofac

您好我想从Ninject切换到AutoFac,但我遇到了一些问题。错误是:

  

Controllers.API.Basic.AddressController'没有默认值   构造

我在启动时注册了这个:

var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

builder.RegisterType<AddressRepository>().As<IBaseRepository<Address>>();

builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());

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

这是我的控制者:

public class AddressController : GenericBaseController<Address>
{
    public AddressController(IBaseRepository<Address> repository)
        : base(repository)
    {
    }

我错过了什么吗?这适用于Ninject。

1 个答案:

答案 0 :(得分:5)

找到它:

// Set the dependency resolver for Web API.
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

我设置它之后就可以了