Tuesday 6 December 2011

Lazy Dependencies in C#

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>

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:

Code Snippet
  1. var lazy = new Lazy<Bar>();
  2.  
  3. // Value is initialized only when referenced for the first time
  4. Bar bar = lazy.Value;

Bar will automatically be created using reflection.

But you can also provide your own initializer like this:

Code Snippet
  1. new Lazy<Bar>(() => new Bar());

So to see this in action say we had a class called Foo with a dependency called Bar:

Code Snippet
  1. public class Foo
  2. {
  3.     private Bar _bar;
  4.     public Foo(Bar bar)
  5.     {
  6.         this._bar = bar;
  7.     }
  8.  
  9.     public void UseBar()
  10.     {
  11.         Console.WriteLine(string.Format("Using: {0}", _bar.GetType().FullName));
  12.     }
  13. }
  14.  
  15. public class Bar
  16. {
  17.     public Bar()
  18.     {
  19.         Thread.Sleep(3000);
  20.         Console.WriteLine("Bar created");
  21.     }
  22. }

But bar is expensive and takes 3 seconds to create.

If we create foo and supplied bar:

Code Snippet
  1. var sw = new Stopwatch();
  2. sw.Start();
  3. var foo = new Foo(new Bar());
  4. sw.Stop();
  5. Console.WriteLine(sw.ElapsedMilliseconds);
  6. foo.UseBar();

we would see this:

image

The construction takes 3 seconds.

If we replace this with:

Code Snippet
  1.  
  2. public class FooSolution
  3. {
  4.     private Lazy<Bar> _bar;
  5.     public FooSolution(Lazy<Bar> bar)
  6.     {
  7.         this._bar = bar;
  8.     }
  9.  
  10.     public void UseBar()
  11.     {
  12.         Bar bar = _bar.Value;
  13.         Console.WriteLine(string.Format("Using: {0}", bar.GetType().FullName));
  14.     }
  15. }

And used it like this:

Code Snippet
  1.  
  2. foo = new FooSolution(new Lazy<Bar>(() => new Bar()));
  3. foo.UseBar();

Now foo is created instantly and bar is only created when we actually use it

image

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

Code Snippet
  1. #if NOT_RUNNING_ON_4
  2.     public class Lazy<T> where T : class
  3.     {
  4.         Func<T> _resolver;
  5.  
  6.         public Lazy(Func<T> resolver)
  7.         {
  8.             this._resolver = resolver;
  9.         }
  10.  
  11.         public Lazy()
  12.         {
  13.             this._resolver = () => Activator.CreateInstance<T>();
  14.         }
  15.  
  16.         T _instance = null;
  17.  
  18.         public T Value
  19.         {
  20.             get
  21.             {
  22.                 if (_instance == null)
  23.                 {
  24.                     _instance = this._resolver();
  25.                 }
  26.                 return _instance;
  27.             }
  28.         }
  29.     }
  30. #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.

Sunday 4 December 2011

IoC for ASP.NET

With my last post where I showed what and how you could create your own IoC container, I was literally inundated by criticism from 1 developer. The criticism was that the I lacked a good example and the why.

What I wanted to do in this post is to show how you can do this in an old ASP.NET application. As for answering the why, there are plenty of posts like this one, with very good discussions and reasoning in both directions.

Now first let me repeat the most important idea. The idea is to use DI, and an IoC Container is just a tool to help achieve this.

There are other benefits like for instance the ability to replace object mappings in one place instead of refactoring code in many places to replace one type for another.

In the stackoverflow post you can scroll down to Joel Spolsky's comment, and just read the reasoning behind why you shouldn’t care about this and stop reading and be done.

But if you're interested to see how this can be done in ASP.NET, and maybe you can spot what you like about it then keep reading.

I found some solutions but not many that I liked or felt that it was good enough and a lot ended up needing a hack here and there.

So let me start by what I wanted to achieve. To Illustrate I will create this very simple page.

Code Snippet
  1. public partial class MyDIPage : System.Web.UI.Page, IDIExampleView
  2. {
  3.     private DIExamplePresenter _presenter;
  4. }

This page uses an MVP pattern, so the page implements a view that will be used by the presenter.

Code Snippet
  1. public interface IDIExampleView
  2. {
  3.     string Data { get; set; }
  4. }

And this is the presenter.

Code Snippet
  1. public class DIExamplePresenter
  2. {
  3.     private IDIExampleView _view;
  4.     private DIExampleDao _dao;
  5.     public DIExamplePresenter(
  6.         IDIExampleView view,
  7.         DIExampleDao dao)
  8.     {
  9.         this._dao = dao;
  10.         this._view = view;
  11.     }
  12. }

This page also needs a presenter so normally I would just construct one as follows:

Code Snippet
  1. this._presenter = new DIExamplePresenter(this, new GenericDao(new SqlContext));

There are also dependencies to a IDataContext, and potentially 2 different implementations that I made up for this example but it would be similar in the real world.

What I wanted instead is for the Global.asax to be the composition root as apposed to each individual page . This is the place we compose our object graph.

So this means that we can now instead of newing up or figuring out where to get our dependencies in each page, we can simply define our constructor and ask for the dependencies we need.

Code Snippet
  1. public MyDIPage(DIExamplePresenter presenter)
  2.     : this()
  3. {
  4.     this._presenter = presenter;
  5. }

Now my page can simply get the dependencies passed in instead of trying to new it up.

For this to work though I need to put a little bit of framework in place.

You will need to create a handler factory, this is not really that complex, well actually it’s as simple as copy and pasting some sample code off some guys blog post like this one. All the instructions and code are there, and then it is not very hard to modify it to work for your case. In the blog post he is using the common service locator to resolve components, but I have created a different flavour which I will show you next.

The article shows exactly how to add the handler class and what to add to the config.The most important part of the article and the handler is the GetHandler that will be called when a page is requested. This will get a page instance and pass it to a function to inject dependencies. A little bit like this:

Code Snippet
  1. private void InjectDependencies(object page)
  2.         {
  3.             Type pageType = page.GetType().BaseType;
  4.  
  5.             var ctor = GetInjectableCtor(pageType);
  6.  
  7.             if (ctor != null)
  8.             {
  9.                 var supportedInterfaces = ExtractViewInterfaces(pageType);
  10.  
  11.                 object[] arguments = (
  12.                     from parameter in ctor.GetParameters()
  13.                     select GetInstance(parameter.ParameterType, supportedInterfaces, page))
  14.                     .ToArray();
  15.  
  16.                 ctor.Invoke(page, arguments);
  17.             }
  18.         }

Each one of the page dependencies will then be resolved by a function called GetInstance where we will use StructureMap to resolve it.

Instead of using the Common ServiceLocator we will just reference our Ioc container of choice. This for me turned out to be StructureMap . Why? Because it was VERY easy to use and seems to fit very well with ASP.NET. You can follow the link or simply in your visual studio extension manager find the nuget package and add it.

So now we have a handler factory, and we can set up structure map:

Code Snippet
  1. public class Global : System.Web.HttpApplication
  2.   {
  3.       void Application_Start(object sender, EventArgs e)
  4.       {
  5.           // Code that runs on application startup
  6.           ObjectFactory.Initialize(x =>
  7.               {
  8.                   x.For<IDataContext>().Use<MemoryContext>();
  9.                  
  10.               });
  11.       }
  12.   }

You will see that I did not register anything for Presenter and GenericDao. That is because these are concrete types, structuremap can simply activate them with reflection. I could of course remap GenericDao to another subclass, but to keep things simple I wont be doing this.

So now we can simply resolve dependencies in the handler factory:

Code Snippet
  1. public class CustomPageHandlerFactory : PageHandlerFactory
  2. {
  3.      private object GetInstance(Type type)
  4.      {
  5.          return ObjectFactory.GetInstance(type);
  6.      }
  7. }

But wait there is a problem:

If you look at the page now its constructor has a dependency on Presenter, and Presenter has a dependency on the Page. We have a circular dependency. This is one of the main reasons that if you search for solutions you will find plenty of ones using property injection instead to avoid this. But because we have an empty parameterless constructor which is called first we can still set the instance first and then inject the dependencies via the overloaded constructor.

One other thing that is a problem is that the dependency is actually to the view interface and not the page type which the handler created.

So to make this work for the Views in the MVP framework they must have one ultimate ancestor. If you have more than one you could also define this in the handler factory if you have to but this is what I did:

Code Snippet
  1. public static List<Type> ExtractViewInterfaces(Type type)
  2. {
  3.     var supportedInterfaces = new List<Type>();
  4.  
  5.     foreach (var intf in type.GetInterfaces())
  6.     {
  7.         if (typeof(IView).IsAssignableFrom(intf))
  8.         {
  9.             supportedInterfaces.Add(intf);
  10.         }
  11.     }
  12. }

What this function does is extract all the view interfaces from the page type and then before resolving the page I tell StructureMap to use special explicit arguments to replace the view dependencies now the handler factory's getinstance looks like this:

Code Snippet
  1. private object GetInstance(Type type, List<Type> supportedInterfaces, object pageInstance)
  2. {
  3.     ExplicitArgsExpression expression = null;
  4.     foreach (var intf in supportedInterfaces)
  5.     {
  6.         if (expression == null)
  7.         {
  8.             expression = ObjectFactory.With(intf, pageInstance);
  9.         }
  10.         else
  11.         {                  
  12.             expression = expression.With(intf, pageInstance);
  13.         }
  14.     }
  15.  
  16.     var instance = expression == null ? ObjectFactory.GetInstance(type) : expression.GetInstance(type);
  17.  
  18.     return instance;
  19. }

Now you can simply declare your dependencies in the constructor of the page. Whether you add constructor dependencies, or move them around. And best of all it doesn’t interfere with existing non DI pages, and there is no deep dependency on the container its just simple clean DI.

Wednesday 23 November 2011

Building your own IoC Container

I have been meaning to do a series on IoC containers so I finally thought of starting with this introduction. 

Before getting into the details let me just introduce you to the problem. IoC is all about DI and object creation.

In fact you can think a little bit about an abstract factory. Except with one major difference and that is the client class never even knows about the existence of the IoC Container (factory). I found this blog where this is actually explained very nicely by a simple table:

Dependency Injection as compared with Abstract Factory.
Characteristic DI AF
Is responsible for instantiating classes? Yes Yes
Class needs to know details of the created object? No No
Class needs to explicitly request creation of desired object? No Yes
Class is dependent upon the DI/Factory that creates objects on its behalf? No Yes

Another good explanation:

From Castle Windsor's Website:

Inversion of Control is a principle used by frameworks as a way to allow developers to extend the framework or create applications using it. The basic idea is that the framework is aware of the programmer's objects and makes invocations on them.

This is the opposite of using an API, where the developer's code makes the invocations to the API code. Hence, frameworks invert the control: it is not the developer code that is in charge, instead the framework makes the calls based on some stimulus.

There is another explanation on Wikipedia

Those sites do a real good job of explaining the concept that can be hard to understand.

The most important thing to understand is that IoC Containers are JUST tools and even though they may be described as patterns your code should not depend on them and it is merely a tool to facilitate dependency injection. Their job is to remove concrete references or instantiations in the code base and restrict it to one place called the Composite root.

Now before you dive in, there are LOTS of these frameworks already written and I mean lots, at first I thought there were many, but then i found Scott Hanselman’s blog on the containers available and they are even more.

Building your own

So if there are so many ones out there and they have so many features why would you even bother?

Because when i show you how incredibly simple and little code the most basic implementation is you will get a better understanding what it is about and what you might expect out of a library if you plan to use one in the future.

And since it is only about a screen full of code it is easy to absorb.

Lets say I have some Interfaces:

Code Snippet
  1. public interface IFoo
  2.     {
  3.         void DoSomething();
  4.     }
  5.  
  6.     public interface IBar { }

IFoo is something that implements some functionality and IBar will just pretend to be some dependency.

Then I have some objects implementing Foo

Code Snippet
  1. public class FooBase : IFoo
  2.     {
  3.         private IBar _bar;
  4.  
  5.         public FooBase(IBar bar)
  6.         {
  7.             this._bar = bar;
  8.         }
  9.  
  10.         public void DoSomething()
  11.         {
  12.             Console.WriteLine(string.Format("{0} doing something to {1}"this.GetType().FullName, this._bar.GetType().FullName));
  13.         }
  14.     }
  15.  
  16.     public class FooImplementation1 : FooBase
  17.     {
  18.         public FooImplementation1(IBar bar)
  19.             : base(bar)
  20.         {
  21.         }   
  22.     }
  23.  
  24.     public class FooImplementation2 : FooBase
  25.     {
  26.         public FooImplementation2(IBar bar)
  27.             : base(bar)
  28.         {
  29.         }  
  30.     }

Then we can also create 1 or 2 dummy example IBar dependencies:

Code Snippet
  1. public class Bar1 : IBar { }
  2.  
  3. public class Bar2 : IBar { }

Now you can probably imagine that normally we would create these objects something like:

Code Snippet
  1. IFoo foo = new FooImplementation1(new Bar1());

But that is of course hardcoding all the concrete implementations and dependencies manually.

Using an IoC container it looks like this:

Code Snippet
  1. var container = new Container()
  2.     .Bind<IFoo, FooImplementation1>()
  3.     .Bind<IBar, Bar1>();

You create your container  in your composition root, and map the types to your concrete implementations.

Then you resolve your objects:

Code Snippet
  1. var foo = container.Resolve<IFoo>();
  2. foo.DoSomething();

The container knows that IFoo is mapped to concrete type FooImplementation1, and that a dependency is required to IBar, it can then also resolve that instance since we also provided it.

Here is how to build this incredibly simple container:

Code Snippet
  1. public class Container
  2.     {
  3.         Dictionary<Type, Func<object>> _resolvers;
  4.  
  5.         public Container()
  6.         {
  7.             this._resolvers = new Dictionary<Type, Func<object>>();
  8.         }
  9.  
  10.         public Container Bind<T, U>()
  11.         {
  12.             return this.Bind<T>(() => (T)this.ActivateInstance(typeof(U)));
  13.         }
  14.  
  15.         public Container Bind<T>(Func<T> resolver)
  16.         {
  17.             this._resolvers[typeof(T)] = () => resolver();
  18.             return this;
  19.         }
  20.  
  21.         public object Resolve(Type type)
  22.         {
  23.             Func<object> ctor = null;
  24.             if (this._resolvers.TryGetValue(type, out ctor))
  25.             {
  26.                 return ctor();
  27.             }
  28.             throw new Exception(string.Format("Cannot resolve type: {0}", type.FullName));
  29.         }
  30.  
  31.         public T Resolve<T>()
  32.         {
  33.             return (T)this.Resolve(typeof(T));
  34.         }
  35.  
  36.         private object ActivateInstance(Type type)
  37.         {
  38.             var constructor = type.GetConstructors()[0];
  39.             var parameters = constructor.GetParameters();
  40.             var inputParameters = new object[parameters.Length];
  41.             for (int i = 0; i < inputParameters.Length; i++)
  42.             {
  43.                 var parameter = parameters[i];
  44.                 inputParameters[i] = Resolve(parameter.ParameterType);
  45.             }
  46.             return constructor.Invoke(inputParameters);
  47.         }
  48.        
  49.     }

That’s it!, that is all the code. Of course even though this example is a little naive it may work for you just as is in the real word, will fall a bit short of the many edge cases you may run into in the real world. But that is OK, even though you could use this understanding and dive right into the more mature frameworks. Or you could extend this example and create providers or wrappers to some of the other libraries out there which can probably be a good idea if you may decide to change in the future. Even if some may argue that this is not necessary.

You will notice that there are 2 ways to bind objects first is to map an interface to a concrete class. The second is to map an interface to a lambda function that provides the concrete instance. Just adding this very simple method makes it quite a bit more flexible so you could do this:

Code Snippet
  1.  
  2. var foo3 = container
  3.     .Bind<IFoo>(() => new FooImplementation1(container.Resolve<IBar>()))
  4.     .Resolve<IFoo>();
  5.  
  6. foo3.DoSomething();

That’s it for this article. Look for future posts where I will be looking at other frameworks and cases that you will run into and want to deal with.