|
InstanceScope
Instance scope determines how an instance is shared between requests for the same service
Autofac2 When a request is made for a service, Autofac can return a single instance (single instance scope), a new instance (per dependency scope) or a single instance within some kind of context, e.g. a thread or an HTTP request (per lifetime 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. For a deeper discussion read an Autofac Lifetime Primer. Per DependencyAlso called 'transient' or 'factory' in other containers. Using per-dependency scope, a unique instance will be returned from each request for a service. This is the default if no other option is specified. builder.RegisterType<X>(); // or builder.RegisterType<X>().InstancePerDependency(); Single InstanceUsing single instance scope, one instance is returned from all requests in the parent and all nested containers. builder.RegisterType<X>().SingleInstance(); Per Lifetime ScopeThis scope applies to nested lifetimes. A component with per-lifetime scope will have at most a single instance per nested lifetime scope. This is useful for objects specific to a single unit of work, e.g. an HTTP request, as a nested lifetime can be created per unit of work. If a nested lifetime is created per HTTP request, then any component with per-lifetime 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.RegisterType<X>().InstancePerLifetimeScope(); The default ASP.NET and WCF integrations are set up so that InstancePerLifetimeScope() will attach a component to the current web request or service method call. ContextualContextual scope is similar to per-lifetime 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->request->transation) components can be configured to be shared at a particular level in the hierarchy using tags. builder.RegisterType<X>().InstancePerMatchingLifetimeScope(MyContextHierarchy.UserSession); The supplied tag value is associated with a lifetime scope: var userSessionLifetime = container.BeginLifetimeScope(); userSessionLifetime.Tag = MyContextHierarchy.UserSession; | |