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?
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")));