如何使用Ninject在构造函数中使用必需的连接字符串绑定类?

时间:2015-07-25 07:31:20

标签: c# ninject

如何使用Ninject在构造函数中使用必需的连接字符串绑定类?

以下是我正在使用的课程:

AppService 类:

namespace SomeProject.LayerB;
{
    public class SomeRepository : ISomeRepository
    {
        private readonly SomeDbContext context;

        public SomeRepository(SomeDbContext context)
        {
            this.context = context;
        }

        // other codes ...
    }
}

SomeRepository 类:

namespace SomeProject.LayerB;
{
    public class SomeDbContext : DbContext
    {
        public SomeDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        // other codes ...
    }  
}

SomeDbContext 类:

namespace SomeProject.LayerC;  
{
    public class SomeModule : NinjectModule
    {
        public override void Load()
        {
            Bind<ISomeRepository>().To<SomeRepository>();

            // My problem is on this part.. I want to provide the connection string on the
            // main program, not here on this class.
            // Bind<SomeDbContext>().ToSelf().WithConstructorArgument("nameOrConnectionString", "the connection string I want to inject");
        }
    } 
} 

然后,我使用包含以下代码的 Ninject模块

using SomeProject.LayerA;
using SomeProject.LayerC;

namespace SomeProject.LayerD;
{
    public class MainProgram
    {
        public MainProgram()
        {
            IKernel kernel = new StandardKernel(new SomeModule());

            AppService appService = kernel.Get<AppService>();
        }
    }  
}

主程序

$input = array('item1' => 'object1', 'item2' => 'object2', 'item-n' => 'object-n');
$new_array = array_values($input);

print '<pre>';
print_r($new_array);
print '</pre>';

注意:主程序可以引用的唯一层是AppA类所在的LayerA,以及找到ninject模块的LayerC。

1 个答案:

答案 0 :(得分:0)

添加如下的配置类:

public class Config
{
    public static string ConnectionString { get; set; }
}

并在你的ninject模块中写下:

Bind<SomeDbContext>().ToSelf()
   .WithConstructorArgument("nameOrConnectionString", 
       c => Config.ConnectionString);  

然后在您的主要方法中,您可以写下以下内容:

public class MainProgram
{
    public MainProgram()
    {
        IKernel kernel = new StandardKernel(new SomeModule());
        Config.ConnectionString = "The connection string";
        AppService appService = kernel.Get<AppService>();
    }
}  

更新:

如果您不想使用静态方法,也可以使用ninject找到config类:

class Config2
{
    public string ConnectionString { get; set; }
}
模块中的

Bind<Config2>().ToSelf().InSingletonScope();
Bind<SomeDbContext>().ToSelf()
   .WithConstructorArgument("nameOrConnectionString",
       c=>c.Kernel.Get<Config2>().ConnectionString);

在main中:

IKernel kernel = new StandardKernel(new SomeModule());
var conf = kernel.Get<Config2>();
conf.ConnectionString = "The connection string";
AppService appService = kernel.Get<AppService>();