ASP.NET MVC 3,RavenDB和Autofac Issue Plus 2其他Autofac问题

rya*_*zec 8 dependency-injection autofac ravendb asp.net-mvc-3

注意:这里有3个问题,我没有提出单独的问题,因为它们都与相同的代码有些相关.

我有以下代码,根据应用程序的生命周期,在Application_Start中注册与RavenDB的连接:

var store = new DocumentStore { Url = "http://localhost:8080" };
store.Initialize();

builder.RegisterInstance(store).SingleInstance();
Run Code Online (Sandbox Code Playgroud)

现在这个工作正常,这应该是每个应用程序的生命周期只应创建一次.现在我想将DocumentSession添加到Autofac中,所以我尝试在Application_Start中添加:

var session = store.OpenSession();
builder.RegisterInstance(session).SingleInstance();
Run Code Online (Sandbox Code Playgroud)

在我的UserRepository中,我有以下构造函数:

 public UserRepository(DocumentStore store, DocumentSession session)
Run Code Online (Sandbox Code Playgroud)

当我尝试运行它时,我得到以下运行时错误:

无法解析构造函数'Void .ctor(Raven.Client.Document.DocumentStore,Raven.Client.Document.DocumentSession)'的参数'Raven.Client.Document.DocumentSession Session'

对我来说这个错误听起来像Autofac并不认为它有DocumentSession但是store.OpenSession()返回它应该是这样.有人知道会导致这个错误吗?我没有正确设置会话变量(它与存储变量工作正常)?

与上述问题有关或可能没有关系的另一件事是如何根据请求而不是按应用程序生命周期向Autofac添加对象实例?虽然RavenDB DocumentStore对象只应该在生命应用程序周期中创建一次,但是应该根据请求创建一次DocumentSession(可能每个应用程序级别创建它会导致上面的错误).

关于Autofac(与上面的代码有点相关)的​​最后一个问题是关于释放对象.如果你看看这个教程:

http://codeofrob.com/archive/2010/09/29/ravendb-image-gallery-project-iii-the-application-lifecycle.aspx

最后一段代码:

ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
Run Code Online (Sandbox Code Playgroud)

这段代码的目的是防止会话泄露.现在这是我还需要担心的Autofac,如果是这样,我将如何在Autofac中执行此操作?

Jim*_*lla 11

我猜你想要的东西:

builder.Register(c => c.Resolve<DocumentStore>().OpenSession()).InstancePerLifetimeScope();
Run Code Online (Sandbox Code Playgroud)

"默认的ASP.NET和WCF集成已设置,以便InstancePerLifetimeScope()将组件附加到当前Web请求或服务方法调用." - Autofac:InstanceScope

基本上,在Web应用程序中,InstancePerLifetimeScope每个HTTP上下文方面处理一个,并且还处理实现的任何类型IDisposable.