I'm trying to use Autofac with WebApi controllers. I have :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
AutofacConfig.Register();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Here is my AutofacConfig:
public class AutofacConfig
{
public static IContainer Container { get; private set; }
public static void Register()
{
var builder = new ContainerBuilder();
// Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
//Register repositories and services.
Container = builder.Build();
}
}
Then I'm trying to set DependencyResolver:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Filters.Add(new ExceptionHandlingAttribute());
var container = AutofacConfig.Container;//I have registered controllers here!!!
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
}
But during the request I'm receiving : "Make sure that the controller has a parameterless public constructor".
Also I've tried to set the DependencyResolver in the AutofacConfig class, just like in the tutorial
What's wrong with that?
The error message means that your controller has some dependencies that Autofac doesn't know how to inject them for you. In other words, your controller's constructor has some dependencies (parameters) that needs to be injected but those dependencies (services) themselves haven't been registered in Autofac.
If you share your controller's constructor code we would be able to identify those unregistered dependencies for you.