Does .net core dependency injection support Lazy

前端 未结 4 1721
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 01:49

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 wh

相关标签:
4条回答
  • 2020-12-09 02:19

    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>())
        {
        }
    }
    
    0 讨论(0)
  • 2020-12-09 02:28

    You only need to add a registration for a factory method that creates the Lazy<IRepo> object.

    public void ConfigureService(IServiceCollection services)
    {
        services.AddTransient<IRepo, Repo>();
        services.AddTransient<Lazy<IRepo>>(provider => new Lazy<IRepo>(provider.GetService<IRepo>));
    }
    
    0 讨论(0)
  • 2020-12-09 02:30

    Services that are to be fetched in Lazy will be re-introduced by the factory registration method with the new Lazy of the intended service type and provided for its implementation using serviceProvider.GetRequiredService.

    services.AddTransient<IRepo, Repo>()
            .AddTransient(serviceProvider => new Lazy<IRepo>(() => serviceProvider.GetRequiredService<IRepo>()));
    
    0 讨论(0)
  • 2020-12-09 02:37

    To my opinion, the code below should do the work(.net core 3.1)

    services.AddTransient<IRepo, Repo>();
    services.AddTransient(typeof(Lazy<>), typeof(Lazy<>));
    
    0 讨论(0)
提交回复
热议问题