问题描述
我有一个复杂的类型要注入到webapi控制器中,但是我无法解决这种依赖关系
I have a complex type to inject into a webapi controller and I am unable to resolve this dependency
public class MyController(IMyComplexType)
IMyComplexType
的实现至少具有5个依赖项I1, ... I5
(因此其实现可以接收I1...I5
)
The implementation of IMyComplexType
has at least 5 dependencies I1, ... I5
(so its implementation recieve I1...I5
)
我有一个Bootstrapper类来注册所有依赖项,在一段代码下方显示给您
I have a Bootstrapper class to Register all dependencies, below a snippet of code to show you
public class Bootstrapper
{
public static IUnityContainer ConfigureContainer(ref IUnityContainer container)
{
container.RegisterType<IMyComplexType, MyComplexTypeImplementation>
(
new HierarchicalLifetimeManager()
);
//Registering I1...I5 in the same way with their implementations
}
}
我尝试直接加载Assmebly,因此在我的ConfigureContainer
方法开始时I1 ... I5驻留在Assembly1中
I tried to Load the Assmebly directly, so I1...I5 reside in assembly1, at the begining of my ConfigureContainer
method
Assembly.Load("assembly1");
我还从以下位置复制了UnityResolver: WebApi依赖项注入
Also I have a UnityResolver copied from: WebApi dependency injection
这是我的WebApiConfig:
This is my WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
IUnityContainer container = new UnityContainer();
Bootstrapper.ConfigureContainer(ref container);
config.DependencyResolver = new UnityResolver(container);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
我也尝试删除控制器上的injecton构造函数,并在Post方法中放入如下内容:
I tried also to remove the injecton constructor on my controller and inside the Post method put something like this:
var service = Container.Resolve<IMyComplexType>() or var service = Container.Resolve<MyComplexTypeImplementation>()
我在这里丢东西了吗?
推荐答案
先注册所有构造函数类型,然后再注册其余所有类型.
Register all constructor types first and then the rest.
HttpContext.Current.Application.SetContainer(container);
container.AddNewExtension<Interception>();
c.RegisterType<IYourType,YourType>();
...
futher constructor types here
...
c.RegisterType<IMyComplexType,MyComplexType>();
c.RegisterType<IMyController, MyController>(
new HierarchicalLifetimeManager(),
new InjectionConstructor(typeof(IMyComplexType)));
然后
public static class WebApiBootstrapper
{
public static void Init(IUnityContainer container)
{
GlobalConfiguration.Configure(config =>
{
config.DependencyResolver = new WebApiDependencyResolver(container); // DI container for use in WebApi
config.MapHttpAttributeRoutes();
WebApiRouteConfig.RegisterRoutes(RouteTable.Routes);
});
}
}
这篇关于无法统一注入Web API 2的复杂类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!