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

2024-01-22

我有一个 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));
        }
    }
}

如果你的 api 控制器与你的 web 项目位于不同的程序集中,那么你需要告诉 Autofac 在哪里可以使用 changning 找到你的控制器:

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

To

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

这将指示 Autofac 扫描程序集MyController and 全部注册 ApiController派生类型它在那里找到的东西。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Autofac 和 WebAPI - 默认构造函数错误 的相关文章

随机推荐