Dependency Injection

What is Dependency Injection?

This is a pattern used for decoupling components and layers in the system. The pattern is implemented through injecting dependencies into a component when it is constructed. These dependences are usually provided as interfaces for further decoupling and to support testability.

Pure Dependency Injection (Poor man’s DI)

Pure Dependency Injection uses constructor or property Injection where lower level components are passed using constructors or properties.

DI container

Simplifies the creation of dependencies and also provides benefits like Interception (for Aspect oriented programming) for cross-cutting concerns like logging, caching security etc.

DI style Advantages Disadvantages
Poor Man’s DI Easy to learn
Strongly typed
Rapid Feedback
High maintenance
DI Container Low maintenance

Convention/xml registration

Weakly typed
Harder to learn
Slower feedback

Without DI container

var svc = new ShippingService(new ProductLocator(), new PricingService(), new InventoryService(), new TrackingRepository(new ConfigProvider()), new
 Logger(new EmailLogger(new ConfigProvider())));

With DI Container (Autowiring)

var svc = IoC.Resolve();

Comparing DI Containers

Autofac DryIoc SimpleInjector Unity
Configuration XML/Auto Auto XML/Auto
Custom Lifetimes Yes Yes Yes
Interception Yes Yes Yes
Auto Diagnostics Yes
Speed Average Fast Fast Average

Container compatibility for generics vary especially for the following scenarios and a more detailed analysis is needed with regards to capabilities required by our system

  • Open Generics
  • Covariance & Contravariance
  • Optional parameters
  • Func & Lazy support

Leave a Reply

Your email address will not be published. Required fields are marked *