My favorites | Sign in
Logo
                
Search
for
Updated Dec 08, 2009 by nicholas.blumhardt
InstanceScope  
Instance scope determines how an instance is shared between requests for the same service

When a request is made for a service, Autofac can return a single instance (singleton scope), a new instance (factory scope) or a single instance within some kind of context, e.g. a thread or an HTTP request (context/container scope.)

This applies to instances returned from an explicit Resolve() call, and instances created internally by the container to satisfy the dependencies of another component,

Singleton

Using singleton scope, one instance is returned from all requests in the parent and all nested containers.

builder.Register<X>().SingletonScoped();

Singleton scope is the default, but this can be changed for a specific ContainerBuilder using ContainerBuilder.SetDefaultScope() (not necessarily a good idea though.)

Factory

Also called 'transient' in other containers. Using factory scope, a unique instance will be returned from each request for a service.

builder.Register<X>().FactoryScoped();

Container

Container scope applies to nested containers. A component with container scope will have at most a single instance per nested container.

This is useful for objects specific to a single unit of work, e.g. an HTTP request, as a nested container can be created per unit of work. If a nested container is created per HTTP request, then any component with container scope will have an instance per HTTP request.

This model of configuration allows the equivalent of per-HTTP-request, per-thread etc. in other containers.

builder.Register<X>().ContainerScoped();

The default ASP.NET and WCF integrations are set up so that ContainerScoped() will attach a component to the current web request or service method call.

Contextual

Contextual scope is similar to container scope but provides more explicit control of visibility.

In most applications, only one level of container nesting will be sufficient for representing the scope of units of work. If more levels of nesting are required (e.g. something like global->session->request) components can be configured to be shared at a particular level in the hierarchy using tags.

builder.Register<X>().InContext(MyContextHierarchy.UserSession);

Sign in to add a comment
Hosted by Google Code