Setter 注入无效

Setter Injection not working

我正在做一些例子来理解使用 NInject 的注入...

但最终在注入时出现了混乱..

例如:-

考虑以下示例:-

class Busineesss
{
    FirstInterface targetInter = null;

    [Inject]   //Setter Injection
    public SecondInterface ProInj { get; set; }

    [Inject]  //Ctor Injection
    public Busineesss(FirstInterface inbound)
    {
        targetInter = inbound;
    }

    public void run()
    {
    /*Line:X*/          targetInter.doSomeThing();
    /*Line:Y*/        ProInj.GetSomethingMyName();
    }
}


interface FirstInterface 
{
    void doSomeThing();
}

interface SecondInterface 
{
    void GetSomethingMyName();
}

模块和主要模块:

public class Module : NinjectModule
{
     public override void Load()
     {
        Bind<FirstInterface>().To<FirstImplementer>();
        Bind<SecondInterface>().To<SecondImplementer>();
     }
}

static void Main(string[] args)
    {
        StandardKernel std = new StandardKernel();
        std.Load(Assembly.GetExecutingAssembly());

        FirstInterface obj =   std.Get<FirstInterface>();

        Busineesss b = new Busineesss(obj);  //Injecting Ctor data here
        b.run();
    }

我的理解:- 所以,根据我的理解,我们必须用必要的数据手动调用根 class,然后 Ninject 将自行解决剩余的依赖关系。

  1. 所以,我认为,在 Line:Y 中,它将获得 SecondImplementer 的实例,因为它是在模块。

但我没有得到任何那种东西。我仅在 ProInj.GetSomethingMyName().

行收到空异常
  1. 如果 Ninjector 正在处理注入,那么为什么我应该在根 class 的 ctor 中传递数据,在行 "Busineesss b = new Busineesss(obj);",应该自己照顾吧.. 所以,应该是,我们只需要提到启动 class 名称... 出现这个问题是因为 "My Understanding" 部分中提到的行....

各位朋友能不能帮帮我,在理解这一点,让我能多掌握一点....

提前致谢..

问题是您 new 正在启动 Busineesss 服务,而您应该从容器中解析它。替换:

FirstInterface obj =   std.Get<FirstInterface>();
Busineesss b = new Busineesss(obj);

与:

Busineesss b = std.Get<Busineesss>();

应该可以解决您的问题。