When do you use Setter Injection over Constructor Injection and vice versa ?
Constructor Injection is normally the standard for dependency injection. Constructor Injection, ensures that all the dependency objects are initialized before we attempt to invoke any methods or peroperties, thus avoiding null reference exceptions.
Setter Injection is used rarely in exceptional cases. For example, if I have a class that has several methods which does not depend on any other objects, and now I need to introduce a new method with in this class, which depends on another object. We can use, constructor injection here, but we need to change the exisitng constructor calls at all the other places. This can become cumbersome, especially if the project is a huge one. Hence, Setter Injection could be a choice when we want to change the legacy code.
Setter Injection, enables you to inject the object, just before you need it. So, if the object is an expensive object to create, and you want to create it as late as possible, then setter injection is your choice.
What are the advantages of using Dependency Injection?
1. Dependency Injection allows us to develop very loosely coupled systems.
2. Easy to swap in a different implementation of a component, as long as the component implements the interface type.
3. Dependency Injection, allows objects to be mocked with in the Unit Tests. This is the greatest advantage of Dependency Injection.
What Dependency Injection Container have you used in your project?
There are lot of Dependency Injection Containers available in the market. I have included, the very commonly used list of Dependency Injection Containers for your quick refernce.
1. Unity
2. Castle Windsor
3. StructureMap
4. Spring.NET
I have used Unity in most of my projects.
If you can improve any of these answer further, please feel free to do so by submitting the form below. Thank you very much for your contribution.
Dependency Injection, allows objects to be mocked with in the Unit Tests. This is the greatest advantage of Dependency Injection.i did not understand,can u plz explain?
ReplyDeleteDependency Injection, allows objects to be mocked with in the Unit Tests. This is the greatest advantage of Dependency Injection.i did not understand,can u plz explain?
ReplyDelete