72 lines
1.5 KiB
C#
72 lines
1.5 KiB
C#
|
#if NET5_0_OR_GREATER
|
||
|
using Microsoft.Extensions.DependencyInjection;
|
||
|
#endif
|
||
|
|
||
|
namespace BITKit.Packages.Core.LazyLoad
|
||
|
{
|
||
|
public interface ILazyLoad
|
||
|
{
|
||
|
bool IsLoaded { get; }
|
||
|
}
|
||
|
|
||
|
public interface ILazyLoad<T> : ILazyLoad
|
||
|
{
|
||
|
T Value { get; }
|
||
|
bool TryGetValue(ref T value);
|
||
|
}
|
||
|
|
||
|
public abstract class LazyLoad<T> : ILazyLoad<T>
|
||
|
{
|
||
|
public bool IsLoaded
|
||
|
{
|
||
|
get
|
||
|
{
|
||
|
if (_value is null)
|
||
|
Load();
|
||
|
return _value is not null;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private T _value;
|
||
|
|
||
|
public T Value
|
||
|
{
|
||
|
get
|
||
|
{
|
||
|
if (_value is null)
|
||
|
Load();
|
||
|
return _value;
|
||
|
}
|
||
|
protected set => _value = value;
|
||
|
}
|
||
|
|
||
|
public bool TryGetValue(ref T value)
|
||
|
{
|
||
|
if (IsLoaded)
|
||
|
{
|
||
|
value = Value;
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
Load();
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
protected abstract void Load();
|
||
|
}
|
||
|
|
||
|
#if NET5_0_OR_GREATER
|
||
|
public class ServiceLoader<T> : LazyLoad<T>
|
||
|
{
|
||
|
protected override void Load()
|
||
|
{
|
||
|
if (BITApp.ServiceProvider is null) return;
|
||
|
if (BITApp.ServiceCollection is null) return;
|
||
|
var service = BITApp.ServiceProvider.GetService<T>();
|
||
|
if (service is null) return;
|
||
|
Value = service;
|
||
|
}
|
||
|
}
|
||
|
#endif
|
||
|
}
|