NOTE: There are 3 questions in here and I did not make separate questions since they are all somewhat related to the same code.
我有以下代码,根据应用程序的生命周期,在Application_Start中注册与RavenDB的连接:
var store = new DocumentStore { Url = "http://localhost:8080" };
store.Initialize();
builder.RegisterInstance(store).SingleInstance();
现在这个工作正常,这应该是每个应用程序的生命周期只应创建一次 . 现在我想将DocumentSession添加到Autofac中,所以我尝试在Application_Start中添加:
var session = store.OpenSession();
builder.RegisterInstance(session).SingleInstance();
在我的UserRepository中,我有以下构造函数:
public UserRepository(DocumentStore store, DocumentSession session)
当我尝试运行它时,我得到以下运行时错误:
Cannot resolve parameter 'Raven.Client.Document.DocumentSession Session' of constructor 'Void .ctor(Raven.Client.Document.DocumentStore, Raven.Client.Document.DocumentSession)'
对我来说这个错误听起来像Autofac并不认为它有DocumentSession但是store.OpenSession()返回它应该是这样 . 有人知道会导致这个错误吗?我没有正确设置会话变量(它与存储变量工作正常)?
与上述问题有关或可能没有关系的另一件事是如何根据请求而不是按应用程序生命周期向Autofac添加对象实例?虽然RavenDB DocumentStore对象只应该在生命应用程序周期中创建一次,但是应该根据请求创建一次DocumentSession(可能每个应用程序级别创建它会导致上面的错误) .
关于Autofac(与上面的代码有点相关)的最后一个问题是关于释放对象 . 如果你看看这个教程:
最后一段代码:
ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
这段代码的目的是防止会话泄露 . 现在这是我还需要担心的Autofac,如果是这样,我将如何在Autofac中执行此操作?
2 回答
我猜你想要的东西:
"The default ASP.NET and WCF integrations are set up so that InstancePerLifetimeScope() will attach a component to the current web request or service method call." - Autofac: InstanceScope
基本上,在Web应用程序中,
InstancePerLifetimeScope
处理每个HTTP上下文方面的一个,并且还处理实现IDisposable
的任何类型 .还存在OpenSession返回IDocumentSession而不是DocumentSession的问题 . 改变我的课程以寻找IDocumentSession以及做Jim所建议的工作,谢谢 .