【发布时间】:2012-10-20 01:43:36
【问题描述】:
在普通的 ASP.MVC 项目中,我们使用 Unity 和来自 http://unitymvc3.codeplex.com/ 的 Unity.Mvc3 包配置依赖解析器
我们在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);
我们创建了一个类似于TestController 的ApiTestController,它继承自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 的关系更大。
谢谢
【问题讨论】:
标签: asp.net-web-api unity-container ioc-container service-locator