欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用.net?core?自帶DI框架實(shí)現(xiàn)延遲加載功能

 更新時(shí)間:2023年02月17日 11:39:01   作者:黑洞視界  
在某些情況,我們希望能延遲一個(gè)依賴的初始化。如果使用的是autofac,我們可以通過(guò)注入Lazy來(lái)實(shí)現(xiàn),這篇文章主要介紹了使用.net?core?自帶DI框架實(shí)現(xiàn)延遲加載,需要的朋友可以參考下

在某些情況,我們希望能延遲一個(gè)依賴的初始化。如果使用的是autofac,我們可以通過(guò)注入Lazy來(lái)實(shí)現(xiàn)。

我們對(duì) autofac GitHub上提供的一個(gè)例子進(jìn)行進(jìn)行簡(jiǎn)單改造,跑起來(lái)看看。
原Example的鏈接https://github.com/autofac/Examples/tree/master/src/AspNetCoreExample

微改后的代碼

[Route("api/[controller]")]
public class ValuesController : Controller
{
    private readonly Lazy<IValuesService> _valuesService;

    public ValuesController(Lazy<IValuesService> valuesService)
    {
        _valuesService = valuesService;
    }

    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        // Kestrel模式下這里會(huì)輸出false,實(shí)例尚未創(chuàng)建
        Console.WriteLine(_valuesService.IsValueCreated); 
        // 調(diào)用Lazy<T>的Value屬性才真正創(chuàng)建實(shí)例
        return this._valuesService.Value.FindAll();
    }
}

直到目前core2.1版本,自帶的DI依舊未支持延遲加載,如果我們嘗試在使用自帶DI的情況下套用上述代碼,會(huì)得到一個(gè)異常,例如:

An unhandled exception occurred while processing the request.

InvalidOperationException: Unable to resolve service for type 'System.Lazy`1[WebApplication9.Services.IValuesService]' while attempting to activate 'WebApplication9.Controllers.ValuesController'.

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

如何利用core自帶的DI實(shí)現(xiàn)呢?如果我們嘗試百度,可能會(huì)搜到類似下面的答案。

services.AddTransient(typeof(Lazy<>));

那么這樣的做法是否能解決我們的問(wèn)題呢,為了簡(jiǎn)化演示代碼。我們創(chuàng)建一個(gè)控制臺(tái)程序并引用Microsoft.Extensions.DependencyInjection。

class Program
{
    static void Main(string[] args)
    {
        var services = new ServiceCollection();
        services.AddScoped<ITestService, TestService>();
        services.AddTransient(typeof(Lazy<>));

        var serviceProvider = services.BuildServiceProvider();

        using (var scope = serviceProvider.CreateScope() )
        {
            var service = scope.ServiceProvider.GetService<Lazy<ITestService>>();
            // 這邊令人遺憾地輸出了true,也就是說(shuō),這種方式的延遲注入是失敗的
            Console.WriteLine(service.IsValueCreated);
        }
    }
}

在查閱Stack Overflow的時(shí)候,我看到了這樣的解決方案,感覺(jué)還是挺簡(jiǎn)單實(shí)用的,分享給大家。

原貼地址:https://stackoverflow.com/questions/44934511/does-net-core-dependency-injection-support-lazyt

public class LazyLoader<T> : Lazy<T>
{
    public LazyLoader(IServiceProvider sp) : base(sp.GetRequiredService<T>)
    {
    }
}

class Program
{
    static void Main(string[] args)
    {
        var services = new ServiceCollection();
        services.AddScoped<ITestService, TestService>();
        // services.AddScoped(typeof(Lazy<>), typeof(LazyLoader<>)); 也可以,區(qū)別不大
        services.AddTransient(typeof(Lazy<>), typeof(LazyLoader<>));

        var serviceProvider = services.BuildServiceProvider();

        using (var scope = serviceProvider.CreateScope())
        {
            var service = scope.ServiceProvider.GetService<Lazy<ITestService>>();
            Console.WriteLine(service.IsValueCreated); // 輸出false

            // 下面輸出true,延遲注入的對(duì)象和正常注入的對(duì)象,本質(zhì)上不會(huì)有差別
            Console.WriteLine(service.Value == scope.ServiceProvider.GetService<ITestService>());
        }
    }
}

實(shí)現(xiàn)原理比較簡(jiǎn)單,在LazyLoader中注入ServiceProvider,調(diào)用父類的Value屬性時(shí)會(huì)執(zhí)行委托,從ServiceProvider中獲取到對(duì)應(yīng)得依賴實(shí)例。

到此這篇關(guān)于使用.net core 自帶DI框架實(shí)現(xiàn) 延遲加載的文章就介紹到這了,更多相關(guān).net core 延遲加載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論