My favorites | Sign in
Logo
                
Search
for
Updated May 19, 2008 by nicholas.blumhardt
TaggedContexts  
Tagged scopes enable inner containers to be structured in a hierarchy.

Introduction

Tagged contexts are useful in applications managing components in a hierarchy of contexts with different lifetimes - e.g. Global/Session/Request/Transaction in a web application.

It is usually only necessary to tag components whose scope matches one of the levels of the hierarchy other than the root or a leaf (e.g. Session and Request in the example above.) This is because the root container will automatically house singletons, and the leaf containers will by default house container- or factory-scoped instances.

Tagging Components and Containers

A tag can be of any type - strings or enumerations are the most common options:

builder.Register(c => new HomeController())
  .InContext("request")
  .ContainerScoped();

var appContainer = builder.Build();
appContainer.TagWith("application");

In this example "application" is the tag applied to the 'global' container in which singleton instances will reside, and "request" is the tag applied to the container servicing HTTP requests:

// A 'request container' is created for every web request
// and disposed of when the request processing completes
var requestContainer = appContainer.CreateInnerContainer();
requestContainer.TagWith("request");

Resolving Instances

In a container without a matching tag or matching parent...

Each component registered in a tagged context will be resolved only in that context - so its child contexts will access instances attached to the parent context. Attempting to resolve HomeController in appContainer will fail.

In a container with a matching tag...

Each requestContainer will have a single unique instance of HomeController because of the ContainerScoped declaration. Factory scope is also supported. Singleton scope works only if the root container matches the component's tag and is thus redundant.

Further nesting...

Sub-containers of requestContainer will be able to resolve HomeController to access the single instance in their parent requestContainer.

If factory scope is used, each request in a sub-container will resolve a new instance, however that instance's lifetime will be bound to requestContainer rather than the subcontainer in which it is resolved.


Sign in to add a comment
Hosted by Google Code