简体   繁体   中英

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

In my .NET Core 3.1 Startup.cs , I'm trying to get the instance of an already registered type ie 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
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM