Browse Source

Add Lazy DI support

pull/324/head
Ionite 1 year ago
parent
commit
9daf2d352a
No known key found for this signature in database
  1. 1
      StabilityMatrix.Avalonia/App.axaml.cs
  2. 25
      StabilityMatrix.Core/Helper/LazyInstance.cs

1
StabilityMatrix.Avalonia/App.axaml.cs

@ -325,6 +325,7 @@ public sealed class App : Application
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddMemoryCache(); services.AddMemoryCache();
services.AddLazyInstance();
var exportedTypes = AppDomain.CurrentDomain var exportedTypes = AppDomain.CurrentDomain
.GetAssemblies() .GetAssemblies()

25
StabilityMatrix.Core/Helper/LazyInstance.cs

@ -0,0 +1,25 @@
using Microsoft.Extensions.DependencyInjection;
namespace StabilityMatrix.Core.Helper;
/// <summary>
/// Lazy instance of a DI service.
/// </summary>
public class LazyInstance<T> : Lazy<T>
where T : notnull
{
public LazyInstance(IServiceProvider serviceProvider)
: base(serviceProvider.GetRequiredService<T>) { }
}
public static class LazyInstanceServiceExtensions
{
/// <summary>
/// Register <see cref="LazyInstance{T}"/> to be used when resolving <see cref="Lazy{T}"/> instances.
/// </summary>
public static IServiceCollection AddLazyInstance(this IServiceCollection services)
{
services.AddTransient(typeof(Lazy<>), typeof(LazyInstance<>));
return services;
}
}
Loading…
Cancel
Save