c# - .net core依赖注入(inject)是否支持Lazy<T>

标签 c# dependency-injection asp.net-core .net-core lazy-initialization

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

配置:

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

Controller :

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> 通用注册的方法这样任何类型都可以延迟解析。

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

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

关于c# - .net core依赖注入(inject)是否支持Lazy<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44934511/

相关文章:

c# - 如何将 URL 地址连接到图像

c# - 如何使用 .NET Framework 获取所有事件的 TCP 连接(无非托管 PE 导入!)?

c# - 在 Windows 窗体中为控件使用通用事件处理程序!

c# - 尝试应用良好的依赖注入(inject)实践时遇到的问题

c# - Entity Framework 代码中所有属性的必需规则优先

c# - 中间件中的路由 Controller 和 Action

c# - 我的线程代码的执行时间没有受益于具有 Join 的线程

c# - 是否使用 TDD 进行构造函数注入(inject)?

delphi - Spring4d : Automatic factory with Owner : TComponent parameter?

asp.net-core - 在 ASP.NET Core Controller 中使用全局变量