D
D
Dmitry Gavrilenko2019-02-20 12:47:27
ASP.NET
Dmitry Gavrilenko, 2019-02-20 12:47:27

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, ....>();

And in some controller I inject through the interface
public class AdminController
{
    private readonly IService _service;
    ctor(IService service)
    {
        _service = service; // <------ ???????????
    }
}

How to achieve controlled injection (I want RAMService to be injected in the current example) without specifying a specific implementation in the constructor (not so! -> ctor(RAMService service))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Filatov, 2019-03-04
@NYMEZIDE

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.

N
netcore, 2019-03-05
@netcore

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));
        }
    }

Use like this:
services.AddScoped<HDDService>();
services.AddScoped<ITenantServiceProvider,TenantServiceProvider>();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question