Thursday 31 January 2013

Basic Usage of Unity for Dependency Injection in MVC 4 Project

First, we need to install Unity Application Block library. If you use NuGet:
PM> install-package Unity.Mvc3
Yes, that is the correct version even for MVC 4 (at least at the time of writing).

Bootstrapper.cs file will be created in the project.

Next, inside Applicaton_Start() in Global.asax.cs, put this code:
Bootstrapper.Initialise();

Then register our components inside BuildUnityContainer() method in Bootstrapper.cs. For example:
        . . .
        container.RegisterType<IColourRepository, ColourRepository>();
        container.RegisterType<IInvoiceRepository, InvoiceRepository>();
        . . .

Calling container.RegisterControllers() in order to register controllers is no longer required in recent version.

Friday 18 January 2013

Singleton in .NET 4.0 or Above

Below is an example of a class that is implementing Singleton pattern in .NET 4.0 or above. The framework added a new type called System.Lazy<T> that makes laziness (lazy construction) really simple and also thread-safe as well. Prior to this we had to use static constructor, double-check locking or other tricks to ensure the laziness and thread-safe.
public sealed class Singleton
{
    private static readonly Lazy<Singleton> _instance =
        new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return _instance.Value; } }

    private Singleton()
    {
        //Console.Write("... Singleton is created ...");
    }
}

We could also use a generic template like this:
public static class Singleton<T> where T : new()
{
    private static readonly Lazy<T> _instance = new Lazy<T>(() => new T());
        
    public static T Instance { get { return _instance.Value; } }
} 
and the class type to be passed:
public class Car
{
    public Car()
    {
        Console.WriteLine("Car is created");
    }
}

References and further reading:
http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx
http://csharpindepth.com/articles/general/singleton.aspx