Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my app, there is one interface and two subclasses.
Two subclasses have been registered as services.
My question is how to control which one to get when i use them?

//HomeController.cs  
public class HomeController : Controller
    {
        public interface ITestDI
        {

        }

        public class TestDIClass1: ITestDI
        {
            public TestDIClass1()
            {
                    
            }
        }
        
        public class TestDIClass2 : ITestDI
        {
            public TestDIClass2()
            {

            }
        }

        ITestDI td;

        public HomeController(ITestDI _td)
        {
            this.td = _td; // how to control which ITestDI implementation will injected with constructor injection? With the configuration below, always get TestDIClass2.
        }

        public IActionResult Index()
        {
            return View();
        }
    } 

//Startup.cs
services.AddScoped<ITestDI, TestDIClass1>();
services.AddScoped<ITestDI, TestDIClass2>();// it seems like TestDIClass2 has overwrited the TestDIClass1.


What I have tried:

if when initialize subclass, a param need to be provided to constructor how to do that?
Posted
Updated 24-Sep-18 13:29pm
v2
Comments
dan!sh 25-Sep-18 1:29am    
DI in core is not same as proper IoC providers. It is a really simple quick to use version. I can think of few ways but that will need class redesign and perhaps factory implementation. Alternate option could be to use a third party IoC provider of choice which will have this feature built in to it.
855 25-Sep-18 2:40am    
Thank you,lw@zi. i just realized that DI in core is not as powerful as other IoC provider.
Could you provide a factory implementation?
dan!sh 25-Sep-18 2:51am    
Here are a couple links: https://dotnetliberty.com/index.php/2016/05/09/asp-net-core-factory-pattern-dependency-injection/ and https://joonasw.net/view/aspnet-core-di-deep-dive. I would personally prefer using AutoFac instead of all this redesign and heavy lifting.
855 25-Sep-18 12:18pm    
It helps, thank you.

services.AddTransient<icontrolpanel>(serviceProvider =>
{
var context = serviceProvider.GetRequiredService<ihttpcontextaccessor>().HttpContext;
var userHeader = context.Request.Headers["loggedInUser"];
if (string.IsNullOrEmpty(userHeader)) return new GuestControlPanel();
if ("admin" == userHeader) return new AdminControlPanel();
return new NormalUserControlPanel(userHeader);
});

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900