我正在开发一个 Web Api,我决定使用自定义 DependencyResolver。我参考了这篇 [Web API 控制器的依赖注入]文章。到目前为止,在将依赖项注入控制器方面,一切都运行良好。我的 Owin 启动类中的配置代码片段
private void RegisterIoC(HttpConfiguration config)
{
_unityContainer = new UnityContainer();
_unityContainer.RegisterType<IAccountService, AccountService>();
.........
.........
config.DependencyResolver = new UnityResolver(_unityContainer);
}
但是在Api 第一次启动时,在UnityResolver 的GetService方法中抛出(但捕获)了一些 ResolutionFailedException。这是异常消息
"Exception occurred while: while resolving.
Exception is: InvalidOperationException -
The current type, System.Web.Http.Hosting.IHostBufferPolicySelector,
**is an interface and cannot be constructed. Are you missing a type mapping?**"
上面抛出以下类型的相同异常
System.Web.Http.Hosting.IHostBufferPolicySelector
System.Web.Http.Tracing.ITraceWriter
System.Web.Http.Metadata.ModelMetadataProvider
System.Web.Http.Tracing.ITraceManager
System.Web.Http.Dispatcher.IHttpControllerSelector
System.Web.Http.Dispatcher.IAssembliesResolver
System.Web.Http.Dispatcher.IHttpControllerTypeResolver
System.Web.Http.Controllers.IHttpActionSelector
System.Web.Http.Controllers.IActionValueBinder
System.Web.Http.Validation.IBodyModelValidator
System.Net.Http.Formatting.IContentNegotiator
我知道这些 ResolutionFailedException 被抛出是因为我没有在我的统一配置中为上述类型提供映射。
现在这是我的问题:-,如果我实现自定义统一 DependencyResolver,我需要定义上述类型的映射,如果需要定义它们对应的默认实现类型,或者是否有一些替代方法来实现 DependencyResolver。即使应用程序现在运行良好,我也很担心,如果无法解决上述类型,以后可能会导致严重问题。请帮忙。
最后一个补充:- 对于以下类型,当我向我的 web api 请求任何操作时,会抛出相同的 ResolutionFailedException
System.Web.Http.Dispatcher.IHttpControllerActivator
System.Web.Http.Validation.IModelValidatorCache
System.Web.Http.Controllers.IHttpActionInvoker