Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Core3.1 framework provided DI – how to get the instance of already registered type?

On .net core 3.1 Startup.cs

Trying to get the instance of already registered type i.e. "IBusinessLogic" using "IServiceCollection", it is not working.

How to get the instance of already registered type in .net core 3.1?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Startup
{
  public void ConfigureServices(IServiceCollection services)
    {    
      container.Register<IBusinessLogic, BusinessLogic>();

      container.AddSingleton<Func<string, string>>
            ((username, password) => new JWTCache(userId, password, 
            container.GetInstance<IBusinessLogic>())); //container.GetInstance<IBusinessLogic>() not working
    }
}

>Solution :

You need to use the overload that gives you an IServiceProvider:

container.AddSingleton<Func<string, string>>(
    sp => (username, password) => new JWTCache(userId, password, sp.GetRequiredService<IBusinessLogic>())
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading