在正常ASP.MVC項目中,我們配置使用Unity和Unity.Mvc3包的依賴解析器從http://unitymvc3.codeplex.com/的WebAPI:訪問子容器作爲一個服務定位器
我們有一個HierarchicalLifetimeManager
container.RegisterType<ITestService, TestService>(new HierarchicalLifetimeManager());
註冊了這個測試服務
我們掛接在Global.asax.cs中與MVC中的容器:
System.Web.Mvc.DependencyResolver.SetResolver(new Unity.Mvc3.UnityDependencyResolver(container));
我們運行這個測試控制器:
public class TestController : Controller
{
private readonly ITestService _service;
public TestController(ITestService service)
{
this._service = service;
}
public ActionResult Test()
{
var locatedService = System.Web.Mvc.DependencyResolver.Current.GetService<ITestService>();
if (_service == locatedService)
return View("Success - Same Service");//This is always the result in an MVC controller
else
throw new Exception("Failure - Different Service Located");//This is never the result in an MVC controller
}
}
但是,在這個項目中,我們添加了一些WebAPI控制器。
我們擁有的global.asax.cs此配置(使用http://unitywebapi.codeplex.com/現在,但我願意接受建議):
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
我們已經創建了一個ApiTestController
類似TestController
從ApiController
繼承,而不是從Controller
。 但是,ApiTestController未通過測試。我知道System.Web.Mvc.DependencyResolver
類和System.Web.Mvc.DependencyResolver.Current
屬性是特定於Mvc。但WebAPI具有相同的功能嗎?
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver.GetService
不起作用,因爲System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver
實例是我配置的父容器。它不是用於將ITestService注入構造函數的子控制器。
該用戶似乎有類似的問題:http://unitywebapi.codeplex.com/discussions/359413 但我覺得這可能與ASP.NET的WebAPI有關,而不是與Unity有關。
感謝
這看起來好像它根本不會創建子請求,因此使用HierarchicalLifetimeManager不會導致每個請求的生命週期,而是一個singleton - 所以依賴關係將在應用程序的生命週期中出現,這可能不是什麼你要。 –