Files
NebulaLauncher/Nebula.Shared/ServiceManager.cs

45 lines
1.3 KiB
C#
Raw Normal View History

2025-01-05 17:05:23 +03:00
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
namespace Nebula.Shared;
public static class ServiceExt
{
public static void AddServices(this IServiceCollection services)
{
2025-01-14 22:10:16 +03:00
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) AddServices(services, assembly);
2025-01-07 17:01:00 +03:00
}
2025-01-14 22:10:16 +03:00
2025-01-07 17:01:00 +03:00
public static void AddServices(this IServiceCollection services, Assembly assembly)
{
foreach (var (type, inference) in GetServicesWithHelpAttribute(assembly))
{
Console.WriteLine("[ServiceMng] ADD SERVICE " + type);
2025-01-05 17:05:23 +03:00
if (inference is null)
services.AddSingleton(type);
else
services.AddSingleton(inference, type);
}
}
2025-01-14 22:10:16 +03:00
private static IEnumerable<(Type, Type?)> GetServicesWithHelpAttribute(Assembly assembly)
{
foreach (var type in assembly.GetTypes())
2025-01-05 17:05:23 +03:00
{
var attr = type.GetCustomAttribute<ServiceRegisterAttribute>();
2025-01-14 22:10:16 +03:00
if (attr is not null) yield return (type, attr.Inference);
2025-01-05 17:05:23 +03:00
}
}
}
public sealed class ServiceRegisterAttribute : Attribute
{
public ServiceRegisterAttribute(Type? inference = null, bool isSingleton = true)
{
IsSingleton = isSingleton;
Inference = inference;
}
2025-01-14 22:10:16 +03:00
public Type? Inference { get; }
public bool IsSingleton { get; }
2025-01-05 17:05:23 +03:00
}