Tom Deleu
Tom Deleu

Reputation: 1187

Autofac - Reuse injected service in component to satisfy other components

Using Autofac, suppose I have a PersonRepository and an EventRepository class, which both depend on a IDataService service... I use both of the repository classes in an Mvc Controller action (for example - might as well be some MvvM WPF application) like

public class Mycontroller : controller
{
   public Mycontroller(PersonRepository personRepo, EventRepository eventRepo) {...}
   ...
   public ActionResult Index(){ ... I use the repository classes in here ...}
}
public class PersonRepository
{
   public PersonRepository(IDataService service){...}
}
public class EventRepository
{
   public PersonRepository(IDataService service){...}
}

I want to make sure, when using the repository classes and injecting them with a IDataService implementation, that both of the repository classes receive the same instance of the IDataService service...

How can I do that?

Upvotes: 1

Views: 483

Answers (3)

Roy Dictus
Roy Dictus

Reputation: 33139

It depends on the lifetime of the IDataService.

Do you want to keep reusing the same one over and over again? Then it's basically a singleton, and you must configure Autofac to treat it as one:

builder.RegisterType<IDataService>().As<MyDataService>().SingleInstance();

But if you're running in MVC and want to reuse the same instance only during the lifetime of the HTTP request, you configure Autofac like so:

builder.RegisterType<IDataService>().As<MyDataService>().HttpRequestScoped();

Upvotes: 3

Valentin V
Valentin V

Reputation: 25739

Try implementing the IComponentLifetime with your rules of reusing and register the services using your lifetime.

Upvotes: 0

SLaks
SLaks

Reputation: 887365

Call the .SingleInstance() method when registering the component. (assuming fluent registration)

Upvotes: 0

Related Questions