Skip to content
Scott Xu edited this page Apr 7, 2014 · 7 revisions

Sometimes it is necessary to defer the resolution of a dependency for reasons such being overly expensive to create during startup and/or being rarely used. In these cases, one can have a Lazy<IDependency> injected instead of IDependency.

When employing this mechanism, the creation of the dependency is deferred until the .Value of the Lazy is accessed for the first time. This lazy-created instance will then be reused for all subsequent accesses to .Value.

The following illustrates how to utilise Lazy<T>-injection:

class Foo
{
    readonly Lazy<Bar> lazyBar;

    public Foo(Lazy<Bar> bar)
    {
        this.lazyBar = bar;
    }
 
    public void Do()
    {
        var bar = this.lazyBar.Value;
        ...
    }
}
</pre>

It is not necessary to perform any `Bind`ings etc. to enable the `Lazy<T>` mechanism; it is processed implicitly  by the default [instance provider](factory-interface%3a-custom-instance-providers) as long as the `Ninject.Extensions.Factory` extension is Loaded into the relevant Kernel.

Clone this wiki locally