Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement a Lazy<T> for DI #5646

Closed
iJungleboy opened this issue May 27, 2023 · 0 comments · Fixed by #5648
Closed

Implement a Lazy<T> for DI #5646

iJungleboy opened this issue May 27, 2023 · 0 comments · Fixed by #5648

Comments

@iJungleboy
Copy link
Contributor

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant