Skip to content

Implement a Lazy<T> for DI #5646

@iJungleboy

Description

@iJungleboy

Description of problem

DNN now has a lot of DI, but it's still missing the classic Lazy<Service>.
This is important to request a service which may not be used, so we don't want to initialize it when not used.

This was already discussed at DNN connect, and I think it's for @bdukes

Description of solution

This is a very classic setup:

  1. Create the 3-lines Lazy-implementation
  2. Register it
  3. Usable
using System;

namespace DotNetNuke.WhateverShouldBeTheNamespace
{
    /// <summary>
    /// Enables lazy requesting of objects - won't be available until needed.
    /// This is a classic plain-vanilla implementation of Lazy for ServiceProviders.
    /// </summary>
    public class LazyImplementation<TService> : Lazy<TService>
    {
        public LazyImplementation(IServiceProvider sp) : base(sp.Build<TService>)
        {
        }
    }
}

Register it like this:

        public static IServiceCollection AddLibDI(this IServiceCollection services)
        {
            // Lazy objects in General
            services.TryAddTransient(typeof(Lazy<>), typeof(LazyImplementation<>));
...

Use like this:

public class MyClass
{
  public MyClass(Lazy<ISomeService> serviceLazy) 
  {
    var actuallyUsed = serviceLazy.Value;
  }

Description of alternatives considered

This is super-standard, so there are not many alternatives (except for not using Lazy, or using a different DI system).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions