Передать параметр в привязку метода

У меня очень простая привязка 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);

Тогда вы можете получить доступ к предоставленной 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();

Теперь, когда это 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();
Другие вопросы по тегам