我正在尝试在 WebApi 模板中使用 IoC 容器。我创建了一个空的 Web App Framework 项目,并选择使用 WebApi。然后,我添加了 Unity NuGet 包并将以下内容添加到 Application_Start:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
UnityConfig.Register();
}
统一配置:
public class UnityConfig
{
public static UnityContainer Register()
{
var container = new UnityContainer();
container.RegisterType<IMyClass, MyClass>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityResolver(container);
return container;
}
}
我的 UnityResolver 在这里(代码大部分是抄袭的,但看起来很标准):
public class UnityResolver : IDependencyResolver
{
protected IUnityContainer container;
public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new UnityResolver(child);
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
container.Dispose();
}
}
当我现在运行它时,出现以下错误:
Unity.Exceptions.ResolutionFailedException: '依赖项解析失败,类型 = 'System.Web.Http.Hosting.IHostBufferPolicySelector',名称 = '(none)'。异常发生时:解决时。异常为: InvalidOperationException - 当前类型 System.Web.Http.Hosting.IHostBufferPolicySelector 是一个接口,无法构造。您是否缺少类型映射? - - - - - - - - - - - - - - - - - - - - - - - - 当时例外,容器是: Resolving System.Web.Http.Hosting.IHostBufferPolicySelector,(none) '
很明显,在告诉它我想使用哪个 IoC 库之后,我需要注入一些内部依赖项,或者告诉它,或者可能更早(或更晚)注册它。
很明显,在告诉它我想使用哪个 IoC 库之后,我需要注入一些内部依赖项,或者告诉它,或者可能更早(或更晚)注册它。
这是真的。您需要注册将通过 Unity 解析的所有类型。错误消息表明您缺少IHostBufferPolicySelector
,因此您需要注册它。
public static UnityContainer Register()
{
var container = new UnityContainer();
// Register all types with Unity here
container.RegisterType<IHostBufferPolicySelector, OwinBufferPolicySelector>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityResolver(container);
return container;
}
我不确定是否OwinBufferPolicySelector
是您需要的,因为您没有提供足够的信息,但您确实需要为其映射一个实现(可能还有其他几个接口)才能继续。
如评论中所述,如果您安装预制 Unity 软件包之一(例如Unity.WebAPI)来提供此实现,则可能会更容易。
如果您遵循ASP.NET Web API 2文档中的依赖注入,它也会有很大帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句