为了在 ASP.NET WebApi 中刷新对 RavenDB 的更改,我创建了以下操作过滤器:
public class RavenDbUnitOfWorkAttribute : ActionFilterAttribute
{
public Func<IDocumentSession> SessionFactory { get; set; }
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var session = SessionFactory.Invoke();
if (session != null && actionExecutedContext.Exception == null)
{
session.SaveChanges();
}
base.OnActionExecuted(actionExecutedContext);
}
}
为了注入(inject) IDocumentSession
我创建了一个自定义 IFilterProvider
循环遍历每个过滤器并使用 setter 注入(inject) (StructureMap) 设置任何依赖项。
我想知道 IFilterProvider
的实例是如何限定范围的。阅读 this article似乎 Controller 是根据请求创建的。
目前,我正在使用 StructureMap 明确界定每个请求的 IDocumentSession
范围。问题是,如果我改为依赖 IDependencyScope
(使用嵌套容器),是否会将相同的 IDocumentSession
实例注入(inject)到我的操作过滤器中?
[更新]
进一步测试,似乎 Action 过滤器不使用与 Controller 相同的依赖范围。但是,我不希望在我的 Controller 中有用于刷新 session 的代码。
最佳答案
正如您在 JabbR 中实际回答的问题一样,使用 HttpRequestMessage
的 GetDependencyScope
扩展方法应该可以解决您的问题:
var session = Request.GetDependencyScope().GetService(typeof(IDocumentSession));
关于structuremap - ASP.NET WebApi 操作过滤器和依赖范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11613592/