4

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

1 Answer 1

10

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.