.net核心依赖项注入是否支持Lazy< T>。 [英] Does .net core dependency injection support Lazy<T>

查看:148
本文介绍了.net核心依赖项注入是否支持Lazy< T>。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用通用的Lazy类来实例化具有.net核心依赖项注入扩展的昂贵类。我已经注册了IRepo类型,但是我不确定Lazy类的注册是什么样的,甚至不支持它。作为解决方法,我使用了 http://mark-dot-net.blogspot.com/2009/08/lazy-loading-of-dependencies-in-unity.html

I am trying to use the generic Lazy class to instantiate a costly class with .net core dependency injection extension. I have registered the IRepo type, but I'm not sure what the registration of the Lazy class would look like or if it is even supported. As a workaround I have used this method http://mark-dot-net.blogspot.com/2009/08/lazy-loading-of-dependencies-in-unity.html

config:

public void ConfigureService(IServiceCollection services)
{
    services.AddTransient<IRepo, Repo>();
    //register lazy
}

控制器:

public class ValuesController : Controller 
{
    private Lazy<IRepo> _repo;

    public ValuesController (Lazy<IRepo> repo)
    {
        _repo = repo;
    }

    [HttpGet()]
    public IActionResult Get()
    {
         //Do something cheap
         if(something)
             return Ok(something);
         else
             return Ok(repo.Value.Get());
    }
}


推荐答案

另一种支持 Lazy< T> 的通用注册的方法,以便可以延迟解析任何类型。

Here's another approach which supports generic registration of Lazy<T> so that any type can be resolved lazily.

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

internal class Lazier<T> : Lazy<T> where T : class
{
    public Lazier(IServiceProvider provider)
        : base(() => provider.GetRequiredService<T>())
    {
    }
}

这篇关于.net核心依赖项注入是否支持Lazy&lt; T&gt;。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆