Fabis
Fabis

Reputation: 2062

Use one instance in multiple components with Autofac

So I have an IApplicationDbContext class and an ApplicationDbContext class that implements it. In the code written by me I use IApplicationDbContext, but higher up on the chain MVC uses ApplicationDbContext and I can't really change that, so at the moment I have registered components like this:

builder.RegisterType<ApplicationDbContext>()
       .AsSelf()
       .InstancePerRequest();
builder.RegisterType<ApplicationDbContext>()
       .As<IApplicationDbContext>()
       .InstancePerRequest();

Which isn't ideal, because I have essentially two instances of the same thing. Is it possible to do something like this?

var dbContextInstance = new ApplicationDbContext();
builder.RegisterInstance(dbContextInstance)
       .As<ApplicationDbContext>()
       .InstancePerRequest(); 
builder.RegisterInstance(dbContextInstance)
       .As<IApplicationDbContext>()
       .InstancePerRequest();

So whenever a constructor needs ApplicationDbContext it uses the ApplicationDbContext instance and whenever it asks for an IApplicationDbContext, it gets that same ApplicationDbContext instance. In the end there is only one instance, but it is used for multiple types. Can I do this somehow?

Upvotes: 0

Views: 228

Answers (1)

Cyril Durand
Cyril Durand

Reputation: 16192

A registration can target more than one service. I would recommend something like this :

builder.RegisterType<ApplicationDbContext>()
       .AsSelf() 
       .As<IApplicationDbContext>()
       .InstancePerRequest();

Upvotes: 4

Related Questions