【发布时间】:2015-01-16 00:03:21
【问题描述】:
我使用以下类作为依赖解析器。参考http://www.asp.net/web-api/overview/advanced/dependency-injection
public class UnityWebAPIResolver : IDependencyResolver
{
protected IUnityContainer container;
public UnityWebAPIResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType); **// This line throws error**
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType); **// This line throws error**
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new UnityWebAPIResolver(child);
}
public void Dispose()
{
container.Dispose();
}
}
在路由配置后的 WebApiConfig 类中,我正在像这样配置依赖解析器
config.DependencyResolver = new UnityWebAPIResolver(UnityConfig.GetContainer());
问题是我遇到了几个这样的错误..
InvalidOperationException - The type IHostBufferPolicySelector does not have an accessible constructor.
InvalidOperationException - The type ModelMetadataProvider does not have an accessible constructor.
InvalidOperationException - The type ITraceManager does not have an accessible constructor.
InvalidOperationException - The type ITraceWriter does not have an accessible constructor.
InvalidOperationException - The type IHttpControllerSelector does not have an accessible constructor.
InvalidOperationException - The type IAssembliesResolver does not have an accessible constructor.
InvalidOperationException - The type IHttpControllerTypeResolver does not have an accessible constructor.
InvalidOperationException - The type IHttpActionSelector does not have an accessible constructor.
InvalidOperationException - The type IActionValueBinder does not have an accessible constructor.
InvalidOperationException - The type IContentNegotiator does not have an accessible constructor.
InvalidOperationException - The type IHttpControllerActivator does not have an accessible constructor.
InvalidOperationException - The type IBodyModelValidator does not have an accessible constructor.
即使我尝试在 global.asax 中执行类似的操作,我也会遇到相同的错误。
GlobalConfiguration.Configuration.DependencyResolver = new UnityWebAPIResolver(UnityConfig.GetContainer());
问题:我的 API 控制器中的所有依赖项似乎都已正确注入,我唯一担心的是它无法解决上述几个 (特定于框架) 类型,是否有可能导致整个框架出现故障并产生随机错误?
【问题讨论】:
-
您必须在某些时候映射自定义类型,这并不是为您神奇地完成的。你有
Unity.config这样做吗? -
是的,我的所有自定义类型都已映射,并且它不会对我的自定义类型抛出任何错误...它只会对未注册到我的容器中的 MVC 框架类型抛出错误..
-
啊,是的,我以前也遇到过这个问题。我修复了它,但我将不得不查看我的源代码以了解如何。给我几个小时,我会发布一个答案。 :)
-
太棒了,当然 :) 并将其发布为您的答案,以便我接受。非常感谢
标签: c# asp.net-web-api unity-container