Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Dependency Injection: Selecting class to instantiate dependency when multiple classes implement the same interface

$
0
0

In my .NET Core project, I have multiple classes that instantiate the same interface. When a controller requests an interface, I'd like to be able to select from among the classes that implement the interface. Is this possible?

Example:

    public class Base1Api : IInterface
    {
        public Base1Api(string root)
        {
            Root = root;
        }       

        public string Root {get; set;}
 }  

public class Base2Api : IInterface
    {
        public Base2Api(string root)
        {
            Root = root;
        }       

        public string Root {get; set;}
 }

Startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            ...

             string root="Test";
             services.AddSingleton<IInterface>(p => new Base1Api(root));
             services.AddSingleton<IInterface>(p => new Base2Api(root));

}

TestController.cs

    public class TestController : Controller
    {

        private IInterface _api=null;
        public TestController(IInterface api) : base()
        {

            //TODO: I'd like to select the interface that implements Base1Api, not Base2Api
            _api = api;
        }

    }


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>