TigerEmu/Utils/DependencyInjectionExtensio...

31 lines
829 B
C#
Raw Permalink Normal View History

2023-09-23 11:11:07 +00:00
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Tiger.Communication.Messages.Interfaces;
namespace Tiger.Utils;
public static class DependencyInjectionExtensions
{
2023-11-10 13:55:42 +00:00
public static void RegisterOnInherited<T>(this IServiceCollection services)
2023-09-23 11:11:07 +00:00
{
var assembly = Assembly.GetExecutingAssembly();
2023-11-10 13:55:42 +00:00
IEnumerable<Type> types;
2023-09-23 11:11:07 +00:00
2023-11-10 13:55:42 +00:00
if (typeof(T).IsInterface)
{
types = assembly.GetTypes()
.Where(t => t.GetInterfaces().Contains(typeof(T)) && !t.IsAbstract);
}
else
{
types = assembly.GetTypes().Where(t => t.BaseType == typeof(T));
}
2023-09-23 11:11:07 +00:00
// Register each type with AddSingleton
2023-10-14 20:32:12 +00:00
foreach (var type in types)
2023-09-23 11:11:07 +00:00
{
2023-10-14 20:32:12 +00:00
services.AddSingleton(typeof(T), type);
2023-09-23 11:11:07 +00:00
}
}
}