-
-
Notifications
You must be signed in to change notification settings - Fork 773
Implement a Lazy<T> for DI #5646
Copy link
Copy link
Closed
Labels
Description
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:
- Create the 3-lines Lazy-implementation
- Register it
- 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).
Reactions are currently unavailable