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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With