Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Delay Object Creation in Dependency Injection

3.67/5 (2 votes)
18 Apr 2016CPOL1 min read 11.9K  
Leverage lazy loading with Unity DI framework

Introduction

When using Dependency Injection, one of the common situations we find ourselves in is the large object graph in the process memory. This is typically because we initialize all objects and register the instances with our unity container at the beginning of the process execution ignoring when and whether they would be needed eventually or not.

Background

Usually, we register types with the container and leverage lazy initialization only for types which have parameter-less constructors.

C#
Container.RegisterType<IStylus, DefaultStylus>("Default");

Whenever we have classes which have to be passed parameters in their constructors, we opt to create their instances and register the instances instead.

C#
var stylus = new WoodenStylus(material);

Container.RegisterInstance<IStylus>(stylus);

This style of coding keeps all the instances in the memory since the process starts irrespective of the fact that when it is needed. It might be possible that the process runs out of memory even before it reaches a stage where it needs the stylus instance.

Solution

However, we can very well register types instead of instances even for types which have constructors with parameters.

C#
Container.RegisterType<IStylus, WoodenStylus>("WoodenStylus", new InjectionFactory((c, t, s) =>
                       new WoodenStylus(
                                material
                               )));

Basically, here we are telling our container to initialize the WoodenStylus object passing material as the parameter as and when needed, rather than initializing it in bootstrap and holding a reference to the same.

This syntax delays the object creation to the point where the object of the type is actually requested by the application.

Using this pattern saves process memory if the application we are dealing with has high number of classes to be injected and all instances have been designed to be short lived.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)