2012-03-01 32 views
11

我想在我的asp.net MVC3項目使用RavenDB與ninject,任何想法,我怎麼也得配置呢?RavenDB與Ninject在ASP.NET MVC3

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

回答

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 
    } 
} 

我希望這有助於!

+0

+1 Ninject使每個請求的會話變得很容易,使用InRequestScope()回答http://bit.ly/HJADY3 – DalSoft 2012-04-16 11:17:31

+0

你在哪裏調用SaveChanges()?我試圖在Application_EndRequest中做到這一點,但沒有運氣。 – Andrew 2012-09-03 09:52:58

+0

我明確地調用了SaveChanges(),當它有意義時,不會在每個請求結束時自動調用。我不知道爲什麼你需要這樣做,或者爲什麼你有問題。我懷疑它與Ninject的操作順序和請求作用域依賴關係有關,儘管沒有一些診斷信息就沒有說明。 – 2012-09-03 13:11:06

7

我推薦使用自定義Ninject提供程序來設置您的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單身。我建議您只需在IDocumentStore實例上使用OpenSession()創建一個新的IDocumentSession,Ninject會在您需要與RavenDB進行交互時爲您提供。 IDocumentSession對象非常輕便,遵循工作單元模式,不是線程安全的,並且意圖在需要時使用並快速處理。

正如其他人做,你也可以考慮執行基礎MVC控制器,它覆蓋OnActionExecuting和OnActionExecuted方法來分別打開會話並保存更改。