DivineInject.GitHub.io

View the Project on GitHub DivineInject

Getting Started

This page explains how to use DivineInject for dependency injection. It assumes you already know what dependency injection is. Basic usage of DivineInject boils down to two topics:

Configuring Bindings

When DivineInject creates a new instance of a class it calls a constructor, each of the constructor arguments is a dependency of the class — something external to the class, for which an implementation must be provided. But how do we know which value to pass for each dependency? This is controlled by the bindings.

Your bindings must be configured near the start of your application — e.g. in the main method or global.asax.

There are basically two ways to configure bindings with DivineInject.

1) bind an interface to a concrete type. DivineInject will pass the same (singleton) instance of the given concrete type whenever it encounters a constructor argument of the interface type.

DivineInjector.Current
	.Bind<IOrdersService>().To<OrdersService>();

2) bind an interface to a specific instance. DivineInject will pass the given instance whenever it encounters a constructor argument of the interface type.

var myOrdersService = new OrdersService(...);
DivineInjector.Current
	.Bind<IOrdersService>().ToInstance(myOrdersService);

Creating Root Objects

DivineInject allows you to create a tree of objects — each object has references to dependencies, which in turn reference their own dependencies; forming a tree of objects. This tree is created starting with the root object — e.g. in a WPF application the root would be the outermost ViewModel; in a WCF application it would be the service class.

The root object is created by calling DivineInject — any arguments the root object constructor requires are taken from the bindings. This should be the only time you explicitly call DivineInject to create objects.

There are two ways of creating the root object:

1) by explicit type:

private MainWindowViewModel CreateViewModel()
{
    return DivineInjector.Current.Get<MainWindowViewModel>();
}

2) by passing the type as an argument:

public object GetInstance(InstanceContext instanceContext, Message message)
{
    return DivineInjector.Current.Get(_instanceType);
}

Having understood how to configure and create singleton objects, read more about scopes in DivineInject.