How do I bind a class which takes its parent class in the constructor with Ninject?

北慕城南 提交于 2019-12-11 21:45:10

问题


I have a class like this:

public class MyClass
{
    public MyClass()
    {
        this.Dependency = new Dependency(this);
    }
}

I want to move the new Dependency() call to the constructor.

public class MyClass
{
    public MyClass(IDependency dependency)
    {
        this.Dependency = dependency;
    }
}

I can't work out how to bind it so that the IDependency is created with the 'this' constructor argument.

Bind<IDependency>()
  .To<Dependency>()
    .WithConstructorArgument("myClass", ctx => ctx.???); // How do I do this?

回答1:


The way your example is laid out, I think you have that backards. MyClass has a dependency on IDependency, so I'd expect you to be doing:

Bind<IMyClass>().To<MyClass>().WithConstructorArgument("dependency", new Dependency());


来源:https://stackoverflow.com/questions/19253827/how-do-i-bind-a-class-which-takes-its-parent-class-in-the-constructor-with-ninje

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!