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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.