Passing a parameter to a 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(); 

I need to replace "somefile.db" with an argument. Something like

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

How do I achieve this?

+4
source share
2 answers

You can provide an optional IParameter when calling Get<T> so that you can register your db name as follows:

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

Then you can access the provided Parameters collection using IContext (sysntax is a bit 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(); 
+2
source

Now that this is NinjectModule, we can use the NinjectModule.Kernel property:

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

Source: https://habr.com/ru/post/1446670/


All Articles