问题
My Web Api app is failing when trying to instantiate an injected controller. I'm using Simple Injector. Bootstrapping the injector is as follows:
[assembly: WebActivator.PostApplicationStartMethod(typeof(SimpleInjectorWebApiInitializer), "Initialize")]
namespace WebApi
{
using System.Web.Http;
using SimpleInjector;
using SimpleInjector.Integration.WebApi;
public static class SimpleInjectorWebApiInitializer
{
public static void Initialize()
{
var container = new Container();
InitializeContainer(container);
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
container.Verify();
GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
}
private static void InitializeContainer(Container container)
{
container.RegisterWebApiRequest<ISomething, Something>();
}
}
}
The controller being injected.
namespace WebApi.Controllers
{
using System.Web.Http;
public class SomethingController : ApiController
{
private readonly ISomething _something;
public SomethingController(ISomething something)
{
_something = something;
}
public string Get()
{
return "Hello world";
}
}
}
The error I keep getting is:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
An error occurred when trying to create a controller of type 'SomethingController'. Make sure that the controller has a parameterless public constructor.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
</error>
What am I missing in configuring Simple Injector
?
回答1:
The assembly with the attribute WebActivator.PostApplicationStartMethod needs to be present in the same directory as the startup project's output directory (i.e. your webapi/bin)
The controller couldn't be constructed properly because Autofac hasn't been set up as the dependency resolver - the Initialise function was never called as the assembly wasn't loaded)
来源:https://stackoverflow.com/questions/25676617/simple-injector-web-api-controller-constructor-injection-failing