将参数传递给方法绑定

5

我有一个非常简单的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个回答

3

在调用Get<T>时,您可以提供额外的IParameter,以便像这样注册您的数据库名称:

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

然后,您可以通过IContext访问提供的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

既然这是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();

NinjectModule有一个公共的Kernel属性,您可以使用它。 - deerchao
谢谢你的帮助,但我觉得我并不真正理解你的意思。Kernel.Get("something")怎么能帮我实现我想要的呢?你能给我一个示例代码片段吗,演示如何传递"somefile.db"参数来创建ISessionFactory片段? - Davita

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接