Same Interface used in different Repository, how can access repository object in controller when we use dependency injection.?
Loading
Same Interface used in different Repository, how can access repository object in controller when we use dependency injection.?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Ajay KumarPosted Oct 7, 2023, 12:49 PM
In the context of dependency injection, if you have multiple implementations of the same interface and you want to use a specific implementation in your controller, you can achieve this by configuring your dependency injection container (such as ASP.NET Core's built-in DI container) to inject the correct implementation of the interface into your controller.
Step 1: Register Implementations with Dependency Injection Container
First, you need to register your interface and its implementations with the dependency injection container. This is usually done in the
Startup.csfile (for ASP.NET Core applications) within theConfigureServicesmethod.In this example,
Implementation1andImplementation2are two different classes implementingIYourInterface.Step 2: Inject the Interface into Your Controller
Next, you can inject the interface into your controller constructor. The DI container will handle the rest, providing the appropriate implementation based on your registration.
Tahir AnsariPosted Oct 7, 2023, 8:42 AM
The Dependency Injection container will resolve and provide the correct repository implementation based on the constructor parameter types.
Use the Correct Repository:
You can now use
_firstRepositoryand_secondRepositoryin your controller actions to access the methods and data provided by each repository. The DI container ensures that you get the appropriate repository instance based on the interface you requested in the constructor.Sachin SinghPosted Oct 7, 2023, 8:40 AM
An interface can point to any concrete object at run time, the behavior is decided by the dependency container if you have registered your IAnimal interface with Cat then IAnimal will be replaced by an object of Cat.