Skip to content

Activation Behaviors

nkohari edited this page Sep 13, 2010 · 1 revision

In many cases, the same instance of a type needs to be used throughout your application. The common way to achieve this goal is via the Singleton pattern. For example:

sealed class Shogun {
  public static readonly Instance = new Shogun();
  private Shogun() { }
  public void RuleWithIronFist() {
    ...
  }
}

The problem with this is you basically have to lock down your type. Doing things this way will make your code end up rigid and inflexible. In particular, it’ll be very difficult to unit test code that’s implemented this way.

Ninject makes it easy to re-use instances that are already created, without having to implement anything via code. All you need is an attribute. For example, to create a singleton:

[Singleton]
class Shogun {
  public void RuleWithIronFist() {
    ...
  }
}

Of course, this behavior will only work for instances requested from the kernel. (Resolving instances is explained in the next section.)

There are four built-in behaviors available in Ninject:

Behavior Class Attribute Meaning
TransientBehavior [Transient] A new instance of the type will be created each time one is requested.
SingletonBehavior [Singleton] Only a single instance of the type will be created, and the same instance will be returned for each subsequent request.
OnePerThreadBehavior [OnePerThread] One instance of the type will be created per thread.
OnePerRequestBehavior [OnePerRequest] One instance of the type will be created per web request, and will be destroyed when the request ends.

Instead of relying on attributes, you can also define the behavior when you declare the binding. This has the same effect as the last example:

Bind<Shogun>().ToSelf().Using<SingletonBehavior>();

This can help if you don’t have access to the source code. You can also define your own behaviors by implementing the IBehavior interface, and even create your own behavior attributes by extending the BehaviorAttributeBase type. This type lets the attribute act as a factory to create an instance of the correct IBehavior implementation. If you extend BehaviorAttributeBase and then decorate your class with your newly-created attribute type, Ninject will pick it up automatically.

If no behavior is specified, the default behavior set for the kernel is used. By default, the StandardKernel will use the TransientBehavior for types without an explicit behavior set, but this can be modified via the kernel options.

Continue reading: Modules and the Kernel