Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac - dependency injection for MVC controller and Web Api controller

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?

like image 917
anilca Avatar asked Dec 25 '22 13:12

anilca


1 Answers

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);
like image 199
Steven Avatar answered Jan 20 '23 10:01

Steven