Beevee
Beevee

Reputation: 198

C# MVC5 AutoFac IoC - Resolve based on requesting class

I'm trying to configure Autofac in a MVC5 project to return a specific implementation of an interface, based on the class that's requesting it.

This is something I have done a lot with PHP using the Laravel framework, which offers a solution like the below:

$this->app->when(PhotoController::class)
          ->needs(Filesystem::class)
          ->give(function () {
              return Storage::disk('local');
          });

So far my Googling has come up short, with most answers suggesting I inject either a Factory (Calling the Container), or the Container it's self, and pull the Service I need from there.

Is there really no way to achieve something similar to the above?

Upvotes: 0

Views: 353

Answers (1)

Péter Csajtai
Péter Csajtai

Reputation: 898

There are options to register conditional dependencies, the easiest with Autofac is the named registration (AFAIK):

builder.Register(c => new DiskStorage()).Named<IStorage>("disk");
builder.Register(c => new PhotoController(c.ResolveNamed<IStorage>("disk")));

Upvotes: 2

Related Questions