Home > Mobile >  .NET Core 3.1 framework provided DI - how to get the instance of already registered type?
.NET Core 3.1 framework provided DI - how to get the instance of already registered type?

Time:11-21

In my .NET Core 3.1 Startup.cs, I'm trying to get the instance of an already registered type i.e. IBusinessLogic using IServiceCollection, but it is not working.

How to get the instance of already registered type in .NET Core 3.1?

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

CodePudding user response:

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>())
);
  • Related