Ninject - 结合带参数的构造函数/实体框架的连接字符串 [英] Ninject - binding constructors with arguments / Entity Framework connection string

查看:127
本文介绍了Ninject - 结合带参数的构造函数/实体框架的连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请原谅我的无知,但我很新的国际奥委会和NinJect。我已经寻找高和低易于理解的解决方案,但到目前为止,他们都躲避我。

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在app / web.config文件中声明的连接字符串创建自己的EF的DbContext:

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

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

但是!我的目标是这样的 - 我知道这语法是胡说八道(我的认为的我可能要IOC MyDbConext太),但我希望的伪code传达我的心愿

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
   {
   }
   ........
}

我将真正AP preciate从IOC / NinJect专家的一些反馈,因为我相信任何模式可以在其他情况下是非常有用的。

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

推荐答案

您可以使用 .WithConstructorArgument()方法指定构造函数参数。第一个参数应该是构造函数参数的名称。

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

}

这篇关于Ninject - 结合带参数的构造函数/实体框架的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆