Autofac和WebAPI - 默认构造函数错误

时间:2014-12-30 15:12:54

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

我有一个webforms项目,但我正在使用WebAPI进行Web服务。我正在尝试实现Autofac。我得到了:

'MyController' does not have a default constructor

根据Autofac文档,我的配置正确,但显然存在问题。我使用的是Visual Studio 2010 / .Net 4.这是我的Application_Start

private void Application_Start(object sender, EventArgs e)
{
    //This enables api controllers in a separate class library
    GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new AssembliesResolver());

    GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

    //Elmah for webapi
    GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());

    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
    json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
    GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

    var builder = new ContainerBuilder();

    //Register DbContext
    builder.RegisterType<MyDbContext>()
        .As<IMyDbContext>()
        .InstancePerRequest();    

    //Register service layer
    var businessLayer = Assembly.GetExecutingAssembly();
    builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
        .Where(t => t.Name.EndsWith("Service"))
        .AsImplementedInterfaces();

    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);

    var container = builder.Build();
    _containerProvider = new ContainerProvider(container);

    var webApiResolver = new AutofacWebApiDependencyResolver(container);        
    GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;       

}

典型的api控制器如下所示:

 [Authorize]
public class MyController : ApiController
{
    public IMyService context { get; set; }

    public MyController(IMyService context)
    {
        this.context = context;
    }

    // GET api/dostuff
    /// <summary>
    /// Get a list of all dtos
    /// </summary>
    /// <returns></returns>
    public IEnumerable<MyDto> Get()
    {
        try
        {                
            return context.MyDtos.ToList();
        }
        catch (Exception ex)
        {
            var message = string.Format("{0} {1} HTTP/1.1 {2} Exception: {3}", Request.Method, Request.RequestUri, HttpStatusCode.MethodNotAllowed, ex.Message);
            var errorMessage = new System.Web.Http.HttpError(message) { { "ErrorCode", 405 } };
            throw new HttpResponseException(ControllerContext.Request.CreateErrorResponse(HttpStatusCode.MethodNotAllowed, errorMessage));
        }
    }
}

1 个答案:

答案 0 :(得分:6)

如果您的api控制器与Web项目不同,那么您需要告诉Autofac在哪里找到具有变化的控制器:

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

builder.RegisterApiControllers(typeof(MyController).Assembly);

这将指示Autofac扫描MyController的所有 ApiController派生类型的程序集。