简体   繁体   English

Autofac,MVC5和OWIN的依赖注入不起作用

[英]Dependency injection with Autofac, MVC5 and OWIN not working

I am having difficulties integrating Autofac with MVC5 and Owin. 我在将Autofac与MVC5和Owin集成时遇到困难。 It seems that MVC is skipping AutofacMvc integration and is still using System.Web.Mvc.DefaultControllerFactory to instantiate a controller, thus throwing 看来MVC正在跳过AutofacMvc集成,并且仍在使用System.Web.Mvc.DefaultControllerFactory实例化控制器,因此抛出

No parameterless constructor defined for this object

There's a great article from Alex Meyer-Gleaves on setting up Owin support for MVC 5 integrations in Autofac . Alex Meyer-Gleaves上有一篇很棒的文章,内容是为Autofac中的MVC 5集成设置Owin支持 I have followed that, and downloaded packages, but still not working. 我已经遵循了这一要求,并下载了软件包,但是仍然无法正常工作。 Here's what my Startup.cs looks like: 这是我的Startup.cs的样子:

public void Configuration(IAppBuilder app)
{ 
    var container = AutofacConfig.Register();
    app.UseAutofacMiddleware(container);  // 1 - setting up autofac middleware (Autofac.Integration.Owin.dll)
    app.UseAutofacMvc(); // 2 - passing on life time scope created in Owin onto MVC request (Autofac.Integration.Mvc.Owin)
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); // 3 - setting dependency resolver for MVC (Autofac.Integration.Mvc)
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

I have checked that my service was registered, my route is invoked successfully if I remove service parameter from constructor. 我已经检查了我的服务是否已注册,如果从构造函数中删除了服务参数,则路由会被成功调用。 What else I might be missing? 我可能还缺少什么? Any hints where the problem might lie would be appreciated. 可能存在问题的任何提示将不胜感激。

Apparently, the problem lied in the fact that I forgot to register controllers into Autofac. 显然,问题在于我忘记将控制器注册到Autofac。 adding this line solved the problem: 添加此行解决了问题:

builder.RegisterControllers(Assembly.GetExecutingAssembly());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM