letsgetsilly
letsgetsilly

Reputation: 1196

Autofac Delegate Factories - How to create a new instance each time?

Question: How do I use the Autofac Factory delegate to create a new instance while within an existing Autofac Lifetime scope?

According to Autofac documentation,

If you register an object as InstancePerDependency() and call the delegate factory multiple times, you’ll get a new instance each time.

This is not true when injecting the factory into the constructor of a class within an existing lifetime scope

Some additional background: I'm attempting to use Autofac Delegate Factories in order to create a new instance of a ValueObject class each time.

This ValueObject class's constructor and delegate factory look like this:

public SlaInMinutes(int slaInMinutes, ISlaCalculator slaCalculator, ITicketUnitOfWork ticketUnitOfWork)
public delegate SlaInMinutes Factory(int slaInMinutes);

Autofac registration looks like this:

builder.RegisterType<SlaInMinutes>().InstancePerLifetimeScope();

When I inject the Factory delegate into a class constructor (SlaInMinutes.Factory slaFactory) within an existing LifetimeScope I am able to instantiate a new class using the Factory parameter, and Autofac takes care of the remaining constructor dependencies. It's great.

Except it's the same instance every time after I instantiate it once. I need to have an new instance each time I call this Factory delegate based on the Factory parameter int slaInMinutes.

Switching my registration from InstancePerLifetimeScope to InstancePerDependency:

 builder.RegisterType<SlaInMinutes>().InstancePerDependency()

does not have the effect of creating a new instance each time I call the Factory method.

What I need:

slaFactory.Invoke(1) //new instance
slaFactory.Invoke(2) //new instance
slaFactory.Invoke(1) //same instance or new instance, don't care

This is an ASP.NET Core 1.0 web app, and the Lifetime scope is started during the beginning of an API endpoint call, and it lasts until that API call is completed.

Upvotes: 5

Views: 1813

Answers (1)

Sham
Sham

Reputation: 930

Remove InstancePerDependency/InstancePerDependency method call from your registration if you want to create new instance for each call.

You can refer to the link https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html?highlight=InstancePerDependency for more details regarding instance scope.

Upvotes: 0

Related Questions