2

我有以下课程(我知道它们设计得不好;我只想表达 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() “你没有使用 DI”。

4

1 回答 1

2

See "inherited constructor arguments" in this blog post from @Remo Gloor. The shouldInherit argument of the ConstructorArgument ctor needs to be passed true for your case to work.

A word of caution - having magic floating arguments like this is not generally a good idea - if something needs to be passed, pass it and don't confuse matters by using container tricks (i.e. what @Steven said in his comment).

(Also obviously if you can Bind ... WithConstructorArgument, that's much better, but I assume you know that.)

Perhaps you're missing an abstraction - maybe the Service should be asking for a ServiceConfiguration rather than two strings that you can easily get backwards?

于 2013-04-23T09:57:24.100 回答