Skip to content

CreateNamedScope and GetScope

Remo Gloor edited this page Aug 1, 2013 · 1 revision

In addition to providing a number of Binding extensions that allow one to declaratively define scoping rules and relationships within Object Composition Graphs, the Named Scope extension provides a facility to enable the programmatic creation of a Named Scope that both acts as a resolution root and as a target that appropriately defined Bindings can link to in order to pool instances and/or benefit from deterministic Disposeal. e.g.

kernel.Bind<IFoo>().To<Foo>().InNamedScope("TheScopeName");
kernel.Bind<IBar>().To<Bar>().InSingletonScope();

using(NamedScope scope = kernel.CreateNamedScope("TheScopeName"))
{
    var foo = scope.Get<IFoo>();
    var bar = scope.Get<IBar>();
}

In the above code, foo will live until scope is Disposed, but bar will live until kernel is Disposed.

Where is CreateNamedScope applicable?

This feature is typically used for low level integration into frameworks that need to create several instances that should be Disposed together. E.g. ASP.NET MVC or NServiceBus integration. For applications, the most specific appropriate declarative mechanism should be used (i.e., select from [[InParentScope]], [[InCallScope]], [[InNamedScope]] prior to resorting to usage of a programmatic mechanism such as this.)

Using CreateScope/GetScope to extend InRequestScope() Bindings to apply to a Custom Request Dispatcher

See this gist and set of code snippets for an illustration of how CreateScope can be used to deterministically Dispose resources upon completion of each Request within a Request Processing loop while continuing to serve as InRequestScope() Bindings.

Related