Ninject - binding constructors with arguments / Entity Framework connection string

JcMaltaDev picture JcMaltaDev · Jul 21, 2011 · Viewed 14.6k times · Source

Please forgive my ignorance, but I am very new to IOC and NinJect. I have searched for high and low for easily understandable solutions but so far they have eluded me.

So far I have the following and all works as expected:

private class StandardModule : NinjectModule
    {
      public override void Load()
      {
        Bind<ILog>().To<NLogLogger>();    // Use NLog
        Bind<IMyEntityFrameWorkRepository().To<MyEntityFrameWorkRepository>();
      }
    }

MyEntityFrameWorkRepository then creates its own EF DbContext via a connection string declared in app/web.config:

public class MyDbContext : DbContext
{
   public MyDbContext() : base("MyAppConfig")
   {
   }
   ........
}

HOWEVER!! My goal is something like this - I realise this syntax is "nonsense" (and I think I may have to IOC MyDbConext too) , but I hope the "pseudo-code" conveys my desire:

private class StandardModule : NinjectModule
{
  public override void Load()
  {
    Bind<ILog>().To<NLogLogger>();    // Use NLog

    string mySqlConnectionString = MyApp.GetCommandLineArgument("sqlconn"); // "Data Source=..."
    Bind<IMyEntityFrameWorkRepository().To<MyEntityFrameWorkRepository>(mySqlConnectionString);
  }
}

.................

public class MyDbContext : DbContext
{
   public MyDbContext( string sqlConnectionString) :
      base(sqlConnectionString) // will accept a standard SQL connection string
   {
   }
   ........
}

I would truly appreciate some feedback from IOC / NinJect experts, since I am sure any "pattern" can be very useful in other scenarios.

Answer

mrydengren picture mrydengren · Jul 21, 2011

You can use the .WithConstructorArgument() method to specify constructor arguments. The first argument should be the name of the constructor parameter.

public class StandardModule : NinjectModule
{
    public override void Load()
    {
        string connectionString = "...";
        Bind<IMyEntityFrameWorkRepository().To<MyEntityFrameWorkRepository>()
            .WithConstructorArgument("sqlConnectionString", connectionString);
    }

}