Reputation: 661
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.
But I did not get any kind of those things. I am getting Null Exception only at the line ProInj.GetSomethingMyName().
Could u friends help me, in understanding this one, So I can grasp a little more....
Thanks in advance..
Upvotes: 0
Views: 196
Reputation: 14580
The problem is you are new
ing 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.
Upvotes: 2