2013-10-27 75 views
0

我想在我的WebAPI解決方案中使用Unity,並試圖從web.config文件加載配置。WebAPI,Unity和Web.config

這是在web.config中團結節:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 
    <assembly name="MyWebAPI" /> 
    <namespace name="MyWebAPI.Controllers" /> 
    <container> 
    <register type="MyController" mapTo="MyController"> 
     <constructor> 
     <param name="param1"> 
      <value value="val1" /> 
     </param> 
     <param name="param2"> 
      <value value="val2" /> 
     </param> 
     <param name="param3"> 
      <value value="val3" /> 
     </param> 
     </constructor> 
     <lifetime type="singleton" /> 
    </register> 
    </container> 
</unity> 

的Bootstrapper.cs:

public static IUnityContainer Initialise() 
{ 
    var container = BuildUnityContainer(); 

    DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 

    return container; 
} 

private static IUnityContainer BuildUnityContainer() 
{ 
    var container = new UnityContainer(); 

    // register all your components with the container here 
    // it is NOT necessary to register your controllers 

    // e.g. container.RegisterType<ITestService, TestService>();  
    RegisterTypes(container); 

    return container; 
} 

public static void RegisterTypes(IUnityContainer container) 
{ 
    container.RegisterType<MyController>(); 
    container.LoadConfiguration(); 
} 

在Global.asax:

protected void Application_Start() 
    { 
     GlobalConfiguration.Configure(WebApiConfig.Register); 
     Bootstrapper.Initialise(); 
    } 

但這不是工作我作爲參數沒有進入構造函數。

的的WebAPI控制器構造:

public MyController(string param1, string param2, string param3) 
    { 
     _param1 = param1; 
     _param2 = param2; 
     _param3 = param3; 
    } 

回答

3

相反MVC DependencyResolver的,使用Web API的具體GlobalConfiguration解析器。例如:

GlobalConfiguration.Configuration.DependencyResolver = 
    new UnityDependencyResolver(container); 

如果您使用Unity bootstrapper for ASP.NET Web API,則會在安裝時爲您設置。

+1

我試過...我將代碼改爲GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);但現在我收到此錯誤無法加載文件或程序集'System.Web.Http,版本= 4.0.0.0,文化=中立,PublicKeyToken = 31bf3856ad364e35'或其依賴項之一。定位的程序集清單定義與程序集引用不匹配。 (來自HRESULT的異常:0x80131040) – Looking4Help

0

對於Web的API,在您的控制器是基於ApiController類,你應該使用:

GlobalConfiguration.Configuration.DependencyResolver = 
new UnityDependencyResolver(container); 

這意味着

DependencyResolver.SetResolver(
new Unity.Mvc3.UnityDependencyResolver(container)); 

用於註冊團結的依賴解析器的MVC你的應用程序的一面。

(你可以有兩個語句,如果你想註冊團結兩個MVC和的WebAPI)

如果你得到System.Web.Http版本錯誤,然後嘗試從刪除System.Web.Http.dll你的引用並刪除Unit.WebApi。 然後重新添加Unity.WebAPI.5.1 Nuget包,它應該沒問題。