Autofac - dependency injection for MVC controller and Web Api controller

狂风中的少年 提交于 2019-12-20 02:35:45

问题


I have MVC controllers (in Controllers folder) and Web Api controllers (in Api folder) in the same project: Here is the folder structure:

  • Controllers
    • ProductController
  • Api
    • ProductController

Here is my bootstrapper method:

        private static void SetAutofacContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            //builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
            builder.RegisterType<DbFactory>().As<IDbFactory>().InstancePerRequest();

            // Repositories
            builder.RegisterAssemblyTypes(typeof(ProductRepository).Assembly)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces().InstancePerRequest();

            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

I can not inject repositories to my Web Api controllers. Here is the exception I get:

An error occurred when trying to create a controller of type 'ProductController'. Make sure that the controller has a parameterless public constructor.

What am I doing wrong?


回答1:


You haven't set Web API's GlobalConfiguration.Configuration.DependencyResolver; you only set MVC's DependencyResolver.

Add the following line:

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


来源:https://stackoverflow.com/questions/33018250/autofac-dependency-injection-for-mvc-controller-and-web-api-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!