簡體   English   中英

.NET Core 3.1 框架提供 DI - 如何獲取已注冊類型的實例?

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

在我的 .NET Core 3.1 Startup.cs中,我正在嘗試使用IServiceCollection獲取已注冊類型的實例,即IBusinessLogic ,但它不起作用。

如何在 .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
    }
}

您需要使用為您提供IServiceProvider的重載

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM