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.