2012-11-17 46 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