将参数传递给方法绑定

Dav*_*ita 5 .net c# dependency-injection ninject ninject-2

我有一个非常简单的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();
Run Code Online (Sandbox Code Playgroud)

我需要的是用参数替换"somefile.db".类似的东西

kernel.Get<ISessionFactory>("somefile.db");
Run Code Online (Sandbox Code Playgroud)

我如何实现这一目标?

nem*_*esv 3

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

kernel.Get<ISessionFactory>(new Parameter("dbName", "somefile.db", false);
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)