2012-11-17 52 views
4

我有一個非常簡單的Ninject綁定:傳遞參數方法結合

Bind<ISessionFactory>().ToMethod(x => 
    { 
     return Fluently.Configure() 
      .Database(SQLiteConfiguration.Standard 
       .UsingFile(CreateOrGetDataFile("somefile.db")).AdoNetBatchSize(128)) 
      .Mappings( 
       m => m.FluentMappings.AddFromAssembly(Assembly.Load("Sauron.Core")) 
         .Conventions.Add(PrimaryKey.Name.Is(p => "Id"), ForeignKey.EndsWith("Id"))) 
      .BuildSessionFactory(); 
    }).InSingletonScope(); 

我需要的是更換「somefile.db」與爭論。類似的東西

kernel.Get<ISessionFactory>("somefile.db"); 

我該如何做到這一點?

回答

2

可以提供額外的IParameter在叫Get<T>時,這樣你就可以這樣註冊您的數據庫名稱:

kernel.Get<ISessionFactory>(new Parameter("dbName", "somefile.db", false); 

然後您可以通過IContext(sysntax很詳細)訪問提供的Parameters集合:

kernel.Bind<ISessionFactory>().ToMethod(x => 
{ 
    var parameter = x.Parameters.SingleOrDefault(p => p.Name == "dbName"); 
    var dbName = "someDefault.db"; 
    if (parameter != null) 
    { 
     dbName = (string) parameter.GetValue(x, x.Request.Target); 
    } 
    return Fluently.Configure() 
     .Database(SQLiteConfiguration.Standard 
      .UsingFile(CreateOrGetDataFile(dbName))) 
      //... 
     .BuildSessionFactory(); 
}).InSingletonScope(); 
+0

@nemsev非常感謝你:) – Davita

0

現在,這是NinjectModule,我們可以使用NinjectModule.Kernel屬性:

Bind<ISessionFactory>().ToMethod(x => 
    { 
     return Fluently.Configure() 
      .Database(SQLiteConfiguration.Standard 
       .UsingFile(CreateOrGetDataFile(Kernel.Get("somefile.db"))).AdoNetBatchSize(128)) 
      .Mappings( 
       m => m.FluentMappings.AddFromAssembly(Assembly.Load("Sauron.Core")) 
         .Conventions.Add(PrimaryKey.Name.Is(p => "Id"), ForeignKey.EndsWith("Id"))) 
      .BuildSessionFactory(); 
    }).InSingletonScope(); 
+0

不,這是一個NinjectModule派生類... – Davita

+0

NinjectModule具有可用的公共內核屬性。 – deerchao

+0

感謝您的幫助,但我認爲我不太明白您的意思。 Kernel.Get(「something」)如何幫助我實現我想要的。你能給我一個片段如何創建傳遞「somefile.db」作爲參數的ISessionFactory片段? – Davita