Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection Initialization

Please note: I have just started using AutoFac to learn about DI and IoC.

Is dependency injection supposed to be initialized in the controllers constructor?

How is this?

private IMyService iMyService;
public HomeController(IMyServices myService)
{
    iMyService = myService;
}

Different from...

public IMyService iMyService = new MyService();

Lastly, it seems like the dependency still exists.

Edit: Fixed typo, new MyService(); was new IMyService();

like image 515
stink Avatar asked Dec 30 '13 06:12

stink


People also ask

Does dependency injection create a new instance?

You will always have to create a new object by instantiating a class at some point. Dependency injection also requires creating new objects. Dependency injection really comes into play when you want to control or verify the behavior of instances used by a class that you use or want to test.

What is dependency injection with example?

Dependency injection (DI) is a technique widely used in programming and well suited to Android development. By following the principles of DI, you lay the groundwork for good app architecture. Implementing dependency injection provides you with the following advantages: Reusability of code.

How is dependency injection implemented?

Dependency Injection is done by supplying the DEPENDENCY through the class's constructor when creating the instance of that class. The injected component can be used anywhere within the class. Recommended to use when the injected dependency, you are using across the class methods.


1 Answers

Dependency Injection means exactly injection of dependency. It does not say anything about initialization. E.g. if you are injecting dependency which is Singleton, then it can be initialized long before you are injecting it.

Your first code is a usual dependency injection via constructor. Your second code is not dependency injection. Actually it looks odd to me - either you are trying to create instance of interface, which is not possible, or you have bad naming here. If it is just bad naming or typo, then second sample should really look like:

 public IMyService iMyService = new MyServiceImplementation();

But you are not injecting anything here. You are simply creating dependency instance (which makes your controller coupled to dependency implementation).

like image 129
Sergey Berezovskiy Avatar answered Sep 29 '22 09:09

Sergey Berezovskiy