I've created a .NET 4.5 WebApi app and I'm attempting to use SimpleInjector.
Everything seems to register OK - when I do container.Verify()
, my WebApi controller loads with the relevant objects injected into the constructor.
However, when I hit my endpoint, I get the infamous "An error occurred when trying to create a controller of type 'XxxController'. Make sure that the controller has a parameterless public constructor.
My IoC configuration is below:
Startup.IoC.cs
public Container ConfigureIoC(IAppBuilder app)
{
var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
RegisterInstances(container);
GlobalConfiguration.Configuration.DependencyResolver =
new SimpleInjectorWebApiDependencyResolver(container);
app.Use(async (context, next) =>
{
using (AsyncScopedLifestyle.BeginScope(container))
{
await next();
}
});
return container;
}
private void RegisterInstances(Container container)
{
RegisterWebApiControllers(container);
// Other registrations here
container.Verify();
}
private void RegisterWebApiControllers(Container container)
{
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
}
Exception
An error occurred when trying to create a controller of type 'LocationController'. Make sure that the controller has a parameterless public constructor.
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
InnerException
Type 'IP2LocationAPI.Web.Controllers.v1.LocationController' does not have a default constructor
at System.Linq.Expressions.Expression.New(Type type)
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
This answer fixed it for me: https://stackoverflow.com/a/28231437/397852
Basically setting the dependency resolver against the HttpConfiguration
instance rather than the GlobalConfiguration.Configuration
method works;
HttpConfiguration config = new HttpConfiguration
{
DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
};