2017-08-01 49 views
1

我創建了一個.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) 

回答

1

這個答案固定它我:https://stackoverflow.com/a/28231437/397852

基本上將依賴關係解析程序設置爲針對HttpConfiguration實例而非GlobalConfiguration.Configuration方法起作用;

HttpConfiguration config = new HttpConfiguration 
    { 
     DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container); 
    }; 
相關問題