Answer the question
In order to leave comments, you need to log in
How to inject a specific implementation in ASP.NET Core?
Good afternoon!
I've run into a problem that I haven't found a solution to yet.
There is an interface: interface IService { long GetAvailableMemory(); }
There are classes that implement this interface: HDDService, RAMService, ....
Using stock DI from Microsoft, I register services:
services.AddScope<IService, HDDService>();
services.AddScope<IService, RAMService>();
services.AddScope<IService, ....>();
public class AdminController
{
private readonly IService _service;
ctor(IService service)
{
_service = service; // <------ ???????????
}
}
Answer the question
In order to leave comments, you need to log in
learn the Factory method
pattern
in the constructor you need to inject the Factory.
And already in the controller methods you will refer to the Factory -> give me a specific implementation (create it for me)
And then you work with it as usual.
Tenants are called such things. It is mainly used by tenants when you have one code, and depending on the request \ user \ headers, you put different databases. You can also zayuzat here.
public interface ITenantServiceProvider
{
IService Service { get; }
}
public class TenantServiceProvider : ITenantServiceProvider
{
public IService Service { get; private set; }
public TenantServiceProvider(HttpContextAccessor contextAccessor)
{
var controllerName = contextAccessor.HttpContext.GetRouteData().Values["controller"].ToString().ToLower();
if (controllerName.Contains("admin"))
Service = contextAccessor.HttpContext.RequestServices.GetService(typeof(HDDService));
}
}
services.AddScoped<HDDService>();
services.AddScoped<ITenantServiceProvider,TenantServiceProvider>();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question