Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is InstancePerLifetimeScope in Autofac?

Tags:

autofac

Can someone please explain in plain English what the lines of code where I put the question marks do? Or maybe point me to an article that puts light on this. This code is for registering dependencies in an autofac container

var builder = new Autofac.ContainerBuilder();


builder.Register<NHibernateInstance>(c => 
    new NHibernateInstance(ConnString, false))
       .InstancePerDependency();//?????

builder.Register(c => c.Resolve<NHibernateInstance>()
    .GetFactory().OpenSession())
    .As<ISession>()
    .InstancePerLifetimeScope(); //-----?????
like image 418
Foo Avatar asked Jun 05 '13 17:06

Foo


People also ask

What is ILifetimeScope?

An ILifetimeScope tracks the instantiation of component instances. It defines a boundary in which instances are shared and configured. Disposing an ILifetimeScope will dispose the components that were resolved through it. Namespace: Autofac.

Should I use transient or scoped?

Use Transient lifetime for the lightweight service with little or no state. Scoped services service is the better option when you want to maintain state within a request. Singletons are created only once and not destroyed until the end of the Application. Any memory leaks in these services will build up over time.

What is AsImplementedInterfaces?

AsImplementedInterfaces<TLimit>(IRegistrationBuilder<TLimit, ScanningActivatorData, DynamicRegistrationStyle>) Specifies that a type from a scanned assembly is registered as providing all of its implemented interfaces.

What is Autofac C#?

Autofac is an open-source dependency injection (DI) or inversion of control (IoC) container developed on Google Code. Autofac differs from many related technologies in that it sticks as close to bare-metal C# programming as possible.


1 Answers

This is a dependency injection container. The Autofac.ContainerBuilder gets a new container, or registrar you might say.

The builder.Register<NHibernateInstance> is stating that when constructing an NHibernateInstance during the recovery phase (i.e. getting an instance out of the container) this is how it should be built.

The last line is indicating that when resolving an NHibernateInstance the OpenSession method should be called once per the lifetime of the object.

like image 88
Mike Perrenoud Avatar answered Jan 04 '23 08:01

Mike Perrenoud