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();
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With