是否有人成功地使用 IoC 容器将依赖项注入到 ASP.NET WebAPI 控制器中?我似乎不能让它工作。
这就是我现在在做的。
在我的 global.ascx.cs
中:
public static void RegisterRoutes(RouteCollection routes)
{
// code intentionally omitted
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
IUnityContainer container = BuildUnityContainer();
System.Web.Http.GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
t =>
{
try
{
return container.Resolve(t);
}
catch (ResolutionFailedException)
{
return null;
}
},
t =>
{
try
{
return container.ResolveAll(t);
}
catch (ResolutionFailedException)
{
return new System.Collections.Generic.List<object>();
}
});
System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container));
BundleTable.Bundles.RegisterTemplateBundles();
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer().LoadConfiguration();
return container;
}
我的控制器工厂:
public class UnityControllerFactory : DefaultControllerFactory
{
private IUnityContainer _container;
public UnityControllerFactory(IUnityContainer container)
{
_container = container;
}
public override IController CreateController(System.Web.Routing.RequestContext requestContext,
string controllerName)
{
Type controllerType = base.GetControllerType(requestContext, controllerName);
return (IController)_container.Resolve(controllerType);
}
}
它似乎从来没有查看我的统一文件来解决依赖性,我得到了一个错误,如:
试图创建类型为 “ PersonalShopper. Services. WebApi. Controller. ShoppingListController”。 确保控制器具有无参数的公共构造函数。
在 DefaultHttpControllerActivator.Create (HttpControllerContext 控制器上下文,类型控制器类型) 在 System.Web.Http.Dispatcher. DefaultHttpControllerFactory. CreateInstance (HttpControllerContext 控制器上下文,HttpControllerDescriptor 控制器描述器) 在 System.Web.Http.Dispatcher. DefaultHttpControllerFactory. CreateController (HttpControllerContext 控制器上下文,字符串控制器名称) 在 System.Web.Http.Dispatcher. HttpControllerDispatcher. SendAsyncInternal (HttpRequestMessage 请求,取消令牌取消令牌) 在 System.Web.Http.Dispatcher. HttpControllerDispatcher. SendAsync (HttpRequestMessage 请求,取消令牌取消令牌)
控制器看起来像:
public class ShoppingListController : System.Web.Http.ApiController
{
private Repositories.IProductListRepository _ProductListRepository;
public ShoppingListController(Repositories.IUserRepository userRepository,
Repositories.IProductListRepository productListRepository)
{
_ProductListRepository = productListRepository;
}
}
我的联合档案看起来像:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="PersonalShopper.Repositories.IProductListRepository, PersonalShopper.Repositories" mapTo="PersonalShopper.Implementations.MongoRepositories.ProductListRepository, PersonalShopper.Implementations" />
</container>
</unity>
注意,我没有为控制器本身注册,因为在 mvc 的早期版本中,控制器工厂会发现需要解决依赖关系。
我的控制器工厂好像从来没有被调用过。