我有一个非常简单的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");
我如何实现这一目标?
答案 0 :(得分:3)
您可以在调用IParameter
时提供额外的Get<T>
,以便您可以像这样注册您的数据库名称:
kernel.Get<ISessionFactory>(new Parameter("dbName", "somefile.db", false);
然后,您可以通过Parameters
访问提供的IContext
集合(sysntax有点冗长):
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();
答案 1 :(得分: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();