Thursday, May 2, 2019

What happens behind the scenes when I call a "Get" on a class using ninject?

Junior here, bare with me as I try to understand dependency injection with ninject.

I understand I should create a service factory, but as of now my main concern is the overcreation of a httpclient.

So lets say I Bind, and initialize a http client at the start of the application using ninject.

IKernel Container = new StandardKernel();

Container.Bind<IService>.To<Service>().InSingletonScope();

Container.Get<HttpClient>();

Ok my HttpClient class is initialized, and now every class that has IService in the constructor can use that single HttpClient instance.

This is where i'm concerned. In any class that uses the service normally you wouldvar service = new Service();

But the service expects a httpclient parameter, so i would have to new up a instance of the http client to pass it through.

So instead I call a class that uses a kernal in a static method to get a instance of the class, so I do not have to enter any parameters when i "Get" a instance of the object.

var service = SomeClass.StaticMethod<Service>();

public static T StaticMethod<T>(){return Container.Get<T>();}

So when this runs a "Get" on the service object i pass into it, does a brand new instance of the service class get created every time i call this?

What happens behind the scenes when I call a "Get" on a class using ninject? Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team