我正在开发Web Api,我决定使用自定义DependencyResolver。我推荐
this [Dependency Injection for Web API Controllers]文章。到目前为止,依赖注入控制器的所有方面都运行良好。我的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
我使用Unity与WebApi和OWIN / Katana运行同样的问题。
我的解决方案是使用Unity.WebApi Nuget包中定义的UnityDependencyResolver而不是我自己的自定义实现(如上面的@Omar Alani)
Install-Package Unity.WebAPI
请注意,程序包将尝试在App_Start中添加名为UnityConfig.cs的文件(我自己使用的文件名)。
在UnityConfig.cs文件中,包将添加代码以针对GlobalConfiguration.Configuration.DependencyResolver注册容器,这不是我们想要的OWIN。
所以不要使用:
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
改用:
config.DependencyResolver = new UnityDependencyResolver(container);
为了完整性:
我的UnityConfig.cs
public static class UnityConfig { public static void Register(HttpConfiguration config) { var container = new UnityContainer(); // Your mappings here config.DependencyResolver = new UnityDependencyResolver(container); } }
我的Startup.cs
[assembly: OwinStartup(typeof(UnityTest.BusinessLayer.Api.ApiStartup))] namespace UnityTest.BusinessLayer.Api { public partial class ApiStartup { public void Configuration(IAppBuilder app) { app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); HttpConfiguration httpConfig = new HttpConfiguration(); UnityConfig.Register(httpConfig); ConfigureAuth(app); //In App_Start ->Startup.Auth WebApiConfig.Register(httpConfig); app.UseWebApi(httpConfig); } } }