Jed*_*oky 11 ravendb ninject.web.mvc asp.net-mvc-3
我想在我的asp.net mvc3项目中使用带有ninject的RavenDB,不知道我该如何配置它?
kernel.Bind<Raven.Client.IDocumentSession>()
.To<Raven.Client.Document.DocumentStore>()
.InSingletonScope()
.WithConstructorArgument("ConnectionString", ConfigurationManager.ConnectionStrings["RavenDB"].ConnectionString);
Run Code Online (Sandbox Code Playgroud)
Ron*_*rby 25
这就是我的做法:
如果您使用Nuget安装Ninject,您将获得/ App_start/NinjectMVC3.cs文件.在那里:
private static void RegisterServices(IKernel kernel)
{
kernel.Load<RavenModule>();
}
Run Code Online (Sandbox Code Playgroud)
这是RavenModule类:
public class RavenModule : NinjectModule
{
public override void Load()
{
Bind<IDocumentStore>()
.ToMethod(InitDocStore)
.InSingletonScope();
Bind<IDocumentSession>()
.ToMethod(c => c.Kernel.Get<IDocumentStore>().OpenSession())
.InRequestScope();
}
private IDocumentStore InitDocStore(IContext context)
{
DocumentStore ds = new DocumentStore { ConnectionStringName = "Raven" };
RavenProfiler.InitializeFor(ds);
// also good to setup the glimpse plugin here
ds.Initialize();
RavenIndexes.CreateIndexes(ds);
return ds;
}
}
Run Code Online (Sandbox Code Playgroud)
为了完整性,这里是我的索引创建类:
public static class RavenIndexes
{
public static void CreateIndexes(IDocumentStore docStore)
{
IndexCreation.CreateIndexes(typeof(RavenIndexes).Assembly, docStore);
}
public class SearchIndex : AbstractMultiMapIndexCreationTask<SearchIndex.Result>
{
// implementation omitted
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助!
小智 7
我建议使用自定义Ninject Provider来设置RavenDB DocumentStore.首先将它放在注册Ninject服务的代码块中.
kernel.Bind<IDocumentStore>().ToProvider<RavenDocumentStoreProvider>().InSingletonScope();
Run Code Online (Sandbox Code Playgroud)
接下来,添加实现Ninject Provider的这个类.
public class RavenDocumentStoreProvider : Provider<IDocumentStore>
{
var store = new DocumentStore { ConnectionName = "RavenDB" };
store.Conventions.IdentityPartsSeparator = "-"; // Nice for using IDs in routing
store.Initialize();
return store;
}
Run Code Online (Sandbox Code Playgroud)
IDocumentStore需要是一个单例,但不要使IDocumentSession成为单例.我建议您只需在IDocumentStore实例上使用OpenSession()创建一个新的IDocumentSession,只要您需要与RavenDB交互,Ninject就会为您提供.IDocumentSession对象非常轻量级,遵循工作单元模式,不是线程安全的,并且可以在需要时使用并快速处理.
正如其他人所做的那样,您也可以考虑实现一个基本MVC控制器,它分别覆盖OnActionExecuting和OnActionExecuted方法来打开会话并保存更改.