Search code examples
c#dependency-injectionninjectinversion-of-control

Setter Injection not working


I am doing some examples to understand Injection using NInject...

But ended up with confusion in injection..

Ex:-

Consider the following example:-

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();
}

Module and main:

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();
    }

My Understanding:- So, as per my understanding, We have to manually call the root class with necessary data, then the Ninject will solve the remaining dependencies by itself.

  1. So, I thought that, In the Line:Y , it will get the instance of SecondImplementer, since it is defined in the Module.

But I did not get any kind of those things. I am getting Null Exception only at the line ProInj.GetSomethingMyName().

  1. If Ninjector is taking care of injection, then why I should pass the data in the ctor of the root class, in the line "Busineesss b = new Busineesss(obj);", it should be taken care by itself right.. So, it should be like, we have to just mention the startup class name... This question arised because of the line mentioned in the "My Understanding" section....

Could u friends help me, in understanding this one, So I can grasp a little more....

Thanks in advance..


Solution

  • The problem is you are newing up the Busineesss service when you should be resolving it from the container. Replacing:

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

    with:

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

    should solve your problem.