Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve a reference-counted shared instance in Autofac?

I have a service IService that several components depend on. The components come and go depending on user actions.

It so happens that the implementation of IService is expensive, and I want 1 instance shared across all components. So far so good, I can use:

builder.RegisterType<ExpensiveStuff>().As<IService>().SingleInstance();

However, I don't want to ExpensiveStuff to live forever once built; I only want it to exist when one or more components holds a reference to it.

Is there a built in means of achieving this in Autofac?

like image 258
Tom Thorne Avatar asked Feb 27 '26 21:02

Tom Thorne


1 Answers

I think you'll have to make sure that your usage of those dependencies happen within an instance scope.

The Orchard project could be a source of inspiration here. They use a set of scopes for Unit of Work; see the ShellContainerFactory.cs source file.

like image 180
Brandon Joyce Avatar answered Mar 02 '26 13:03

Brandon Joyce