跟进此 question 。我正在研究使用 SimpleInjector 和 WebAPI 的示例。不幸的是,我想利用 WebAPI KB2568167 和 KB2915689 阻止我升级到 .net 4.5。所以我现在只能使用 .net 4.0 & WebAPI v1 (4.0.30506.0)。
有没有办法用旧版本的 WebAPI 复制 RegisterWebApiRequest<T>()
范围?
虽然我的 nu-get 包只包含 .net 4.5 版本,但我能够下载代码并轻松获得框架 4.0 编译。在我的消息处理程序中调用 var container = request.GetDependencyScope()
时,会返回一个 SimpleInjectorWebApiDependencyResolver
类。尝试从容器中检索实例,如下所示:
var poco = (SimplePOCO) container.GetService(typeof(SimplePOCO));
导致以下错误::
我只是在我的配置中遗漏了什么吗?有没有替代方案——比如创建我自己的消息处理程序?
更新
发布 codeplex issue 后,我回到了基础。我采用了一个普通的 Mvc WebApi 项目,引用了我对
SimpleInjector
、 SimpleInjector.Integration.WebApi
和 SimpleInjector.Extensions.ExecutionContextScoping
的编译。像@blueling 一样,我能够让它在消息处理程序中工作。
那么有什么不同呢?我的一个想法是,我的非功能性项目只是骨架——只有 WebApi 和纤薄的 web.config。我的解决方案中没有基础项目模板附带的脚手架和绒毛。明天我计划将工作示例与非工作的一个逐个引用和 web.config 设置进行比较。
更新 2
所以多一点调试,果然在 DependencyResolver 实现上调用了 Dispose(),但不是我......
最佳答案
我能够解决这个问题。我不完全清楚为什么在 SimpleInjectorWebApiDependencyResolver
上调用了 dispose ,但这是我发现的:
BAD 依赖解析器实现是 one listed here 的副本:
public sealed class SimpleInjectorWebApiDependencyResolver : IDependencyResolver
{
private readonly Container container;
public SimpleInjectorWebApiDependencyResolver(Container container)
{
this.container = container;
}
public IDependencyScope BeginScope()
{
return this;
}
public object GetService(Type serviceType)
{
return ((IServiceProvider)this.container).GetService(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return this.container.GetAllInstances(serviceType);
}
public void Dispose()
{
}
}
我注意到我下载的源代码中有一点不同的副本 here 。
public sealed class SimpleInjectorWebApiDependencyResolver : IDependencyResolver
{
private readonly Container container;
private readonly Scope scope;
public SimpleInjectorWebApiDependencyResolver(Container container) : this(container, beginScope: false)
{
Requires.IsNotNull(container, "container");
}
private SimpleInjectorWebApiDependencyResolver(Container container, bool beginScope)
{
this.container = container;
if (beginScope)
{
this.scope = container.BeginExecutionContextScope();
}
}
IDependencyScope IDependencyResolver.BeginScope()
{
return new SimpleInjectorWebApiDependencyResolver(this.container, beginScope: true);
}
object IDependencyScope.GetService(Type serviceType)
{
if (!serviceType.IsAbstract && typeof(IHttpController).IsAssignableFrom(serviceType))
{
return this.container.GetInstance(serviceType);
}
return ((IServiceProvider)this.container).GetService(serviceType);
}
IEnumerable<object> IDependencyScope.GetServices(Type serviceType)
{
return this.container.GetAllInstances(serviceType);
}
void IDisposable.Dispose()
{
if (this.scope != null)
{
this.scope.Dispose();
}
}
}
切换到这个版本后一切正常。我仍然有 CallContext.LogicalGetData 和 Nested Execution Contexts 的潜在问题,正如 @Steven 在评论中指出的那样。因此,请自行承担使用此解决方案的风险。
关于asp.net-web-api - 使用 SimpleInjector 有没有办法用 .net 4/webapi 1 复制 RegisterWebApiRequest<T>()?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22326821/