我在将Autofac与MVC5和Owin集成时遇到了困难。似乎MVC正在跳过AutofacMvc集成,并且仍然使用System.Web.Mvc.DefaultControllerFactory来实例化一个控制器,从而抛出
No parameterless constructor defined for this object
有一篇很棒的文章 Alex Meyer-Gleaves在setting up Owin support for MVC 5 integrations in Autofac。我已经关注了,并下载了包,但仍然无法正常工作。这是我的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);
}
我已经检查过我的服务已注册,如果从构造函数中删除service参数,我的路由会成功调用。还有什么我可能会失踪?任何可能存在问题的提示都将受到赞赏。
答案 0 :(得分:4)
显然,问题在于我忘了将控制器注册到Autofac中。添加此行解决了问题:
builder.RegisterControllers(Assembly.GetExecutingAssembly());