Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter to method binding

I have a very simple Ninject binding:

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();

What I need is to replace "somefile.db" with an argument. Something similar to

kernel.Get<ISessionFactory>("somefile.db");

How do I achieve that?

like image 326
Davita Avatar asked Oct 23 '22 01:10

Davita


1 Answers

You can provide additional IParameters when calling Get<T> so you can register your db name like this:

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

Then you can access the provided Parameters collection through the IContext (the sysntax is little verbose):

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();
like image 135
nemesv Avatar answered Nov 03 '22 02:11

nemesv