SimpleInjector 验证正常,但在第一次请求时抛出无参数构造函数错误

SimpleInjector verifies OK, but throws Parameterless constructor error on first request

我已经创建了一个 .NET 4.5 WebApi 应用程序,并且正在尝试使用 SimpleInjector。

似乎一切正常 - 当我这样做时 container.Verify(),我的 WebApi 控制器加载了注入构造函数的相关对象。

然而,当我到达终点时,我收到臭名昭著的“尝试创建类型 'XxxController' 的控制器时发生错误。确保控制器具有无参数 public 构造函数。

我的 IoC 配置如下:

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);
}

异常

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)

这个答案为我修复了它:

基本上针对 HttpConfiguration 实例而不是 GlobalConfiguration.Configuration 方法设置依赖解析器有效;

HttpConfiguration config = new HttpConfiguration
    {
        DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
    };