我有以下类(我知道它们设计得不好;我只是想表达 Ninject 问题)。
我不知道如何将构造函数参数传递给我的服务(这是 Utility
的依赖项,这是 MainProgram
的依赖项):-
class MainProgram
{
static IKernel kernel;
static MainProgram mainProgram;
Utility Utility;
static void Main(string[] args)
{
kernel = new StandardKernel(new DIModule());
var constructorArgument1 = new ConstructorArgument("firstArg", args[0]);
var constructorArgument2 = new ConstructorArgument("secondArg", args[1]);
mainProgram = kernel.Get<MainProgram>(new IParameter[] { constructorArgument1, constructorArgument2 });
mainProgram.Utility.ExportToXML();
}
public MainProgram(Utility utility)
{
this.utility = utility;
}
}
public class Utility
{
private IService service;
public Utility(IService service)
{
this.service = service;
}
//methods to work with service
}
public class Service : IService
{
private readonly string firstArg;
private readonly string secondArg;
public Service(string firstArg, string secondArg)
{
this.firstArg = firstArg;
this.secondArg = secondArg;
}
}
class DIModule : NinjectModule
{
public override void Load()
{
Bind<IService>().To<Service>();
Bind<Utility>().ToSelf();
Bind<MainProgram>().ToSelf();
}
}
kernel.Get<MainProgram>()
失败并显示以下消息:
Error activating string
No matching bindings are available, and the type is not self-bindable.
我理解这是因为构造函数参数没有进入 IService。
这是否是解决我的依赖关系的正确方法?我在一些地方读到,如果你使用 kernel.Get() “你没有使用 DI”。
最佳答案
参见"inherited constructor arguments" in this blog post from @Remo Gloor 。需要传递 ConstructorArgument
构造函数的 shouldInherit
参数 true
才能使您的案例正常工作。
请注意 - 像这样的神奇 float 参数通常不是一个好主意 - 如果需要传递某些内容,请传递它,不要通过使用容器技巧来混淆问题(即 @Steven 在他的评论中所说的) .
(显然,如果您可以 Bind
... WithConstructorArgument
,那就更好了,但我假设您知道这一点。)
也许您缺少一个抽象 - 也许 Service
应该要求一个 ServiceConfiguration
而不是两个可以轻松向后获取的字符串?
关于c# - 将构造函数参数传递给根对象的依赖项,作为 Ninject 中单个解析的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16157629/