When using dependency injection you might get to a point where you need to supply a dependency on something that is expensive to create, for example:
- A database connection
- An object that takes long to create.
This would be fine if you were definitely using the dependency, but there are scenarios where the dependency might just sometimes be used.
Even though you can inject an abstract factory or a lambda function to evaluate the dependency, this didn’t feel so nice. And also felt like extra effort to define and also to manage the instance variable.
Then I found this post by Jeffrey Palermo explaining the exact same problem. I saw his solution and what I didn’t like about it is that he created a factory inside of a method in his class to create an OrderShipperFactory. With this refactoring it was not clear that the OrderProcessor now depends on the factory as it was not asking for it as a dependency. It is also not possible in this implementation to substitute a different factory. Jefferey went as far calling it constructor over-injection anti-pattern. A statement he relaxed in further posts.
But it turns out that this problem can be solved elegantly in .NET 4 with a new class called:
Lazy<T> solves this problem in 2 ways:
- Lazy load the instance by automatically activating only when used.
- Takes care of recycling the same instance variable.
Using lazy you only need to supply the type like this:
- var lazy = new Lazy<Bar>();
- // Value is initialized only when referenced for the first time
- Bar bar = lazy.Value;
Bar will automatically be created using reflection.
But you can also provide your own initializer like this:
- new Lazy<Bar>(() => new Bar());
So to see this in action say we had a class called Foo with a dependency called Bar:
- public class Foo
- {
- private Bar _bar;
- public Foo(Bar bar)
- {
- this._bar = bar;
- }
- public void UseBar()
- {
- Console.WriteLine(string.Format("Using: {0}", _bar.GetType().FullName));
- }
- }
- public class Bar
- {
- public Bar()
- {
- Thread.Sleep(3000);
- Console.WriteLine("Bar created");
- }
- }
But bar is expensive and takes 3 seconds to create.
If we create foo and supplied bar:
- var sw = new Stopwatch();
- sw.Start();
- var foo = new Foo(new Bar());
- sw.Stop();
- Console.WriteLine(sw.ElapsedMilliseconds);
- foo.UseBar();
we would see this:
The construction takes 3 seconds.
If we replace this with:
- public class FooSolution
- {
- private Lazy<Bar> _bar;
- public FooSolution(Lazy<Bar> bar)
- {
- this._bar = bar;
- }
- public void UseBar()
- {
- Bar bar = _bar.Value;
- Console.WriteLine(string.Format("Using: {0}", bar.GetType().FullName));
- }
- }
And used it like this:
- foo = new FooSolution(new Lazy<Bar>(() => new Bar()));
- foo.UseBar();
Now foo is created instantly and bar is only created when we actually use it
Now in case you are using an older version to .NET 4 you can create this class and then wrap it in a special compiler directive to only declare it for versions prior to this. A very nice stackoverflow post can be found here that explains how to set up this directive.
Here is an implementation of Lazy for pre .NET 4.0
- #if NOT_RUNNING_ON_4
- public class Lazy<T> where T : class
- {
- Func<T> _resolver;
- public Lazy(Func<T> resolver)
- {
- this._resolver = resolver;
- }
- public Lazy()
- {
- this._resolver = () => Activator.CreateInstance<T>();
- }
- T _instance = null;
- public T Value
- {
- get
- {
- if (_instance == null)
- {
- _instance = this._resolver();
- }
- return _instance;
- }
- }
- }
- #endif
What I like about Lazy over an injected factory here is that all we wanted was an instance to use when we needed it. A factory or Func<T> would give us a new instance each time and we would have to create a variable to manage the lifetime.
So it is still a good thing to use Dependency Injection, and most of the time I would not worry about this except if you have a specific performance need or a rare dependency that does have a significant creation hit.
dependency that does have a significant creation hit.