问题描述
如何使用Ninject绑定所需的连接字符串类的构造函数?
How to bind classes with required connection string in constructor using Ninject?
下面是我使用的类:
AppService服务类:
using SomeProject.LayerB;
namespace SomeProject.LayerA;
{
public class AppService
{
private readonly ISomeRepository someRepository;
public LocationManagementService(ISomeRepository someRepository)
{
this.someRepository = someRepository;
}
// other codes ...
}
}
SomeRepository 类:
namespace SomeProject.LayerB;
{
public class SomeRepository : ISomeRepository
{
private readonly SomeDbContext context;
public SomeRepository(SomeDbContext context)
{
this.context = context;
}
// other codes ...
}
}
SomeDbContext 类:
namespace SomeProject.LayerB;
{
public class SomeDbContext : DbContext
{
public SomeDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
// other codes ...
}
}
然后,我用的 Ninject模块包含以下代码:
Then, I use a Ninject module containing the following code:
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");
}
}
}
主要节目
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>();
}
}
}
注意:该主程序可以参考的唯一层是层1.在这里AppService服务类定位和以及LayerC其中ninject模块中找到。
NOTE: The only layer that main program can reference is LayerA where AppService class is located and as well as LayerC where the ninject module is found.
推荐答案
添加配置类是这样的:
public class Config
{
public static string ConnectionString { get; set; }
}
和你ninject模块写的:
and in your ninject module write this:
Bind<SomeDbContext>().ToSelf()
.WithConstructorArgument("nameOrConnectionString",
c => Config.ConnectionString);
然后在你的主要方法,你可以写如下:
then in your main method you could write following:
public class MainProgram
{
public MainProgram()
{
IKernel kernel = new StandardKernel(new SomeModule());
Config.ConnectionString = "The connection string";
AppService appService = kernel.Get<AppService>();
}
}
更新:
您可以使用 ninject
找到配置
类,如果你还不想用静态方法:
You can use ninject
to locate config
class also if you don't want use static methods:
class Config2
{
public string ConnectionString { get; set; }
}
在模块:
Bind<Config2>().ToSelf().InSingletonScope();
Bind<SomeDbContext>().ToSelf()
.WithConstructorArgument("nameOrConnectionString",
c=>c.Kernel.Get<Config2>().ConnectionString);
在主:
IKernel kernel = new StandardKernel(new SomeModule());
var conf = kernel.Get<Config2>();
conf.ConnectionString = "The connection string";
AppService appService = kernel.Get<AppService>();
这篇关于如何使用Ninject绑定与所需的连接字符串类的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!