SimpleInjector验证正常,但在第一次请求时抛出无参数构造函数错误
问题描述:
我创建了一个.NET 4.5 WebApi应用程序,我试图使用SimpleInjector。SimpleInjector验证正常,但在第一次请求时抛出无参数构造函数错误
一切似乎注册好 - 当我做container.Verify()
时,我的WebApi控制器加载与注入构造函数的相关对象。
然而,当我打我的终点,我在尝试创建类型‘XxxController’的控制器时发生了臭名昭著的“错误。请确保该控制器具有一个无参数的公共构造函数。
我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);
}
异常
尝试创建'LocationController'类型的控制器时发生错误。确保控制器有一个无参数的公共构造函数。
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
类型 'IP2LocationAPI.Web.Controllers.v1.LocationController' 没有默认的构造函数
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)
答
这个答案固定它我:https://*.com/a/28231437/397852
基本上将依赖关系解析程序设置为针对HttpConfiguration
实例而非GlobalConfiguration.Configuration
方法起作用;
HttpConfiguration config = new HttpConfiguration
{
DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
};