Search code examples
c#.netdependency-injectionninjectninject-2

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?


Solution

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