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

Eth*_*fer 3 asp.net autofac asp.net-web-api

我有一个webforms项目,但我正在使用WebAPI进行Web服务.我正在尝试实现Autofac.我正进入(状态:

'MyController' does not have a default constructor
Run Code Online (Sandbox Code Playgroud)

根据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;       

}
Run Code Online (Sandbox Code Playgroud)

典型的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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

nem*_*esv 6

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

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
Run Code Online (Sandbox Code Playgroud)

builder.RegisterApiControllers(typeof(MyController).Assembly);
Run Code Online (Sandbox Code Playgroud)

这将指示Autofac扫描组件MyController注册 ApiController它在那里发现的所有派生类型.