37 lines
876 B
C#
37 lines
876 B
C#
using MAX.Core.Infrastructure;
|
|
using System;
|
|
using System.Collections.Concurrent;
|
|
|
|
namespace MAX.Core.DependencyInjection;
|
|
|
|
public interface ILazyServiceProvider
|
|
{
|
|
object LazyGetService(Type serviceType);
|
|
T LazyGetService<T>();
|
|
}
|
|
|
|
public class LazyServiceProvider : SingleInstance<LazyServiceProvider>, ILazyServiceProvider
|
|
{
|
|
protected ConcurrentDictionary<Type, Lazy<object>> CachedServices { get; }
|
|
private LazyServiceProvider()
|
|
{
|
|
CachedServices = new ConcurrentDictionary<Type, Lazy<object>>();
|
|
}
|
|
public virtual T LazyGetService<T>()
|
|
{
|
|
return (T)LazyGetService(typeof(T));
|
|
}
|
|
|
|
public virtual object LazyGetService(Type serviceType)
|
|
{
|
|
return GetService(serviceType);
|
|
}
|
|
public virtual object GetService(Type serviceType)
|
|
{
|
|
return CachedServices.GetOrAdd(
|
|
serviceType,
|
|
_ => new Lazy<object>(() => IocManager.Resolve(serviceType))
|
|
).Value;
|
|
}
|
|
}
|