Autofac and WebAPI - default constructor error
I have a webforms project, but I am using WebAPI for web services. I am trying to implement Autofac. I get:
'MyController' does not have a default constructor
According to the Autofac documentation, I have the correct configuration, but obviously there is a problem. I am using Visual Studio 2010 / .Net 4. Here is my Application_Start
private void Application_Start(object sender, EventArgs e)
{
//This enables api controllers in a separate class library
GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new AssembliesResolver());
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
//Elmah for webapi
GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
var builder = new ContainerBuilder();
//Register DbContext
builder.RegisterType<MyDbContext>()
.As<IMyDbContext>()
.InstancePerRequest();
//Register service layer
var businessLayer = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
var container = builder.Build();
_containerProvider = new ContainerProvider(container);
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
}
A typical api controller looks like this:
[Authorize]
public class MyController : ApiController
{
public IMyService context { get; set; }
public MyController(IMyService context)
{
this.context = context;
}
// GET api/dostuff
/// <summary>
/// Get a list of all dtos
/// </summary>
/// <returns></returns>
public IEnumerable<MyDto> Get()
{
try
{
return context.MyDtos.ToList();
}
catch (Exception ex)
{
var message = string.Format("{0} {1} HTTP/1.1 {2} Exception: {3}", Request.Method, Request.RequestUri, HttpStatusCode.MethodNotAllowed, ex.Message);
var errorMessage = new System.Web.Http.HttpError(message) { { "ErrorCode", 405 } };
throw new HttpResponseException(ControllerContext.Request.CreateErrorResponse(HttpStatusCode.MethodNotAllowed, errorMessage));
}
}
}
+3
source to share
1 answer
If you have your api controllers in a different assembly than your web project, you need to tell Autofac where you can find your controllers with change:
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
To
builder.RegisterApiControllers(typeof(MyController).Assembly);
This will cause Autofac to scan the assembly MyController
and register any ApiController
derived types it finds there.
+6
source to share