Dependency Injection through LightInject

While working on Light Inject last year, I found a dearth of information on the ‘How’ of Light Inject. Don’t get me wrong, I could find plenty of ‘What’. As necessity is the parent of invention (being politically correct here  🙂 ), I decided to venture into the world of blogging. This series of posts for beginners shall shed light on how to use Light Inject in daily practices.

Those of you who are not aware about LightInject, is a Dependency Injection tool just like Unity, Castle Windsor, StructureMap, Spring.Net and many more to name. You can download it from their website http://www.lightinject.net/.

Now lets start with LightInject. The first and most important thing is to create a container. Container will be responsible to give you the instance of specified interface. Lets see how to create a container and register a type and getting an instance of it.

public IDbConnection GetConnection()
{
    var container = new LightInject.ServiceContainer();
    container.Register<IDbConnection, OleDbConnection>();
    return container.GetInstance<IDbConnection>();
}

The line 3 defines a creates an instance of ServiceContainer type. The next line actually defines what object to create when GetInstance method is called for this interface. So we will register an interface with its concrete. One might think what if I want to register multiple type, can I do it with Register? The answer is Yes. Register method have overload where you can specify your service name and every type can have its own service name. This way you can register multiple concrete types of an interface.

container.Register<IDbConnection, OleDbConnection>("OleDb");
container.Register<IDbConnection, SqlConnection>("MsSql");

Above code snippet shows how to register multiple types in a container for an interface.

return container.GetInstance<IDbConnection>("MsSql");

Using the service name we can have an object of needed type. Here “MsSql” is the service name.

Generally, we don’t use Register and GetInstance methods together as it doesn’t serve the purpose. Instead types can be registered in CompositionRoot of an assembly or some other method that is called prior to GetInstance.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s