BITKit/Packages/Runtime~/Core/LazyLoad/ILazyLoad.cs

72 lines
1.5 KiB
C#
Raw Normal View History

2023-06-29 14:57:11 +08:00
#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
}