xkcd
xkcd

Reputation: 2590

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:

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?

Upvotes: 4

Views: 4604

Answers (1)

Steven
Steven

Reputation: 172606

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);

Upvotes: 10

Related Questions