11

我想在我的 asp.net mvc3 项目中使用带有 ninject 的 RavenDB,知道如何配置它吗?

      kernel.Bind<Raven.Client.IDocumentSession>()
              .To<Raven.Client.Document.DocumentStore>()
              .InSingletonScope()
              .WithConstructorArgument("ConnectionString", ConfigurationManager.ConnectionStrings["RavenDB"].ConnectionString);
4

2 回答 2

25

这是我的做法:

如果您使用 Nuget 安装 Ninject,您将获得一个 /App_start/ NinjectMVC3.cs 文件。在那里:

    private static void RegisterServices(IKernel kernel)
    {            
        kernel.Load<RavenModule>();
    }    

这是 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;
    }
}

为了完整起见,这是我的索引创建类:

public static class RavenIndexes
{
    public static void CreateIndexes(IDocumentStore docStore)
    {
        IndexCreation.CreateIndexes(typeof(RavenIndexes).Assembly, docStore);
    }

    public class SearchIndex : AbstractMultiMapIndexCreationTask<SearchIndex.Result>
    {
       // implementation omitted
    }
}

我希望这有帮助!

于 2012-03-06T17:56:06.970 回答
7

我建议使用自定义 Ninject Provider 来设置您的 RavenDB DocumentStore。首先将它放在注册 Ninject 服务的代码块中。

kernel.Bind<IDocumentStore>().ToProvider<RavenDocumentStoreProvider>().InSingletonScope();

接下来,添加实现 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;
}

IDocumentStore 必须是单例,但不要使 IDocumentSession 成为单例。我建议您在需要与 RavenDB 交互时在 Ninject 提供的 IDocumentStore 实例上使用 OpenSession() 简单地创建一个新的 IDocumentSession。IDocumentSession 对象非常轻量级,遵循工作单元模式,不是线程安全的,并且可以在需要的地方使用和快速处理。

正如其他人所做的那样,您还可以考虑实现一个基本 MVC 控制器,该控制器覆盖 OnActionExecuting 和 OnActionExecuted 方法以分别打开会话和保存更改。

于 2012-03-01T20:14:15.203 回答