Friday, August 13, 2010

Hello World with Microsoft Unity framework

Inversion of Control, dependency injection is achieved with the Microsoft Unity Framework. It is a nice framework for making loosely coupled applications.

Add the following references to your project after having installed the Unity application block.
--> Microsoft.Practices.ObjectBuilder2
--> Microsoft.Practices.Unity
--> Microsoft.Practices.Unity.Configuration
--> Microsoft.Practices.Unity.Interception
--> Microsoft.Practices.Unity.Interception.Configuration
--> Microsoft.Practices.Unity.StaticFactory

And then include the following using statement in your code:

using Microsoft.Practices.Unity;

The Hello World program:

using System;
using Microsoft.Practices.Unity;

public interface IHelloWorld
{
    string Text { get; }
}

public class HelloWorld : IHelloWorld
{
    public string Text
    {
        get { return "Hello, World"; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Bootstrapping
        IUnityContainer unityContainer = new UnityContainer();
        unityContainer.RegisterType<IHelloWorld, HelloWorld>(); 

        // Resolving what class is registered with what interface
        var obj = unityContainer.Resolve<IHelloWorld>();

        Console.WriteLine(obj.Text);
    }
}

What's going on above?

1. Define the interface
public interface IHelloWorld

2. Make a implementation
public class HelloWorld : IHelloWorld

3.Bootstrapping: register your interface to any interface implementation
IUnityContainer unityContainer = new UnityContainer();
unityContainer.RegisterType<IHelloWorld, HelloWorld>();

4. Resolving what class is registered with what interface, invoke your code
var obj = unityContainer.Resolve<IHelloWorld>();

5. Resolve what class is associated with our interface. This is how you run/start your class.
var obj = unityContainer.Resolve<IHelloWorld>();

6. And you're ready to print hello, world. Of course you don't need to return a property. You could have done the console writing inside your implementation of the interface.
Console.WriteLine(obj.Text); 

No comments:

Post a Comment