将构造函数参数作为Ninject中单个解析的一部分传递给根对象的依赖项

本文关键字:一部分 依赖 对象 参数 构造函数 Ninject 单个解 | 更新日期: 2023-09-27 18:10:27

我有以下类(我知道它们设计得不好;我只是想表达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>()失败,提示信息如下:

激活字符串

错误
No matching bindings are available, and the type is not self-bindable.

我理解这是因为构造函数的参数没有传递给IService。

这是解决依赖关系的正确方法吗?我在一些地方读到,如果你使用kernel。get ()

将构造函数参数作为Ninject中单个解析的一部分传递给根对象的依赖项

请参阅@Remo Gloor的博客文章中的"继承构造函数参数"。ConstructorArgument函数的shouldInherit参数需要传递给true才能正常工作。

一个警告-有这样的魔法浮动参数通常不是一个好主意-如果需要传递某些东西,传递它,不要使用容器技巧混淆问题(即@Steven在他的评论中所说的)。

(很明显,如果你可以BindWithConstructorArgument,这是更好的,但我假设你知道。)

也许你错过了一个抽象-也许Service应该要求ServiceConfiguration而不是两个字符串,你可以很容易地得到?