using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;
// 自定义属性来标记服务类型
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class ServiceTypeAttribute : Attribute
{
public ServiceLifetime Lifetime { get; }
public ServiceTypeAttribute(ServiceLifetime lifetime)
{
Lifetime = lifetime;
}
}
public static class DependencyInjectionExtensions
{
/// <summary>
/// 批量注册服务
/// </summary>
/// <param name="services">IServiceCollection</param>
/// <param name="servicePrefix">服务类的前缀,例如 "Service"</param>
/// <param name="interfacePrefix">接口的前缀,例如 "I"</param>
public static void RegisterServices(this IServiceCollection services, string servicePrefix, string interfacePrefix)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
// 获取当前程序集中所有类
var types = Assembly.GetExecutingAssembly().GetTypes();
// 筛选出符合服务命名约定的类
var serviceTypes = types
.Where(t => t.Name.StartsWith(servicePrefix) && !t.IsInterface && !t.IsAbstract)
.ToList();
// 遍历所有服务类
foreach (var serviceType in serviceTypes)
{
// 尝试查找对应的接口
var interfaceType = types.FirstOrDefault(t => t.Name == interfacePrefix + serviceType.Name.Substring(servicePrefix.Length) && t.IsInterface);
if (interfaceType != null)
{
// 获取服务类型上的 ServiceTypeAttribute
var serviceTypeAttribute = serviceType.GetCustomAttribute<ServiceTypeAttribute>();
var lifetime = serviceTypeAttribute?.Lifetime ?? ServiceLifetime.Scoped; // 默认使用 Scoped
// 根据不同的生命周期注册服务
switch (lifetime)
{
case ServiceLifetime.Singleton:
services.AddSingleton(interfaceType, serviceType);
break;
case ServiceLifetime.Scoped:
services.AddScoped(interfaceType, serviceType);
break;
case ServiceLifetime.Transient:
services.AddTransient(interfaceType, serviceType);
break;
default:
services.AddScoped(interfaceType, serviceType); // 默认使用 Scoped
break;
}
}
else
{
// 如果没有找到对应的接口,则可以选择只注册服务本身,或者抛出异常
// 这里选择抛出异常,提示开发者需要有对应的接口
throw new InvalidOperationException($"Service {serviceType.Name} does not have a corresponding interface (expected interface name: {interfacePrefix}{serviceType.Name.Substring(servicePrefix.Length)})");
}
}
}
}
// 示例接口和服务
public interface IUserService
{
void DoSomething();
}
[ServiceType(ServiceLifetime.Scoped)] // 使用属性标记生命周期
public class UserService : IUserService
{
public void DoSomething()
{
Console.WriteLine("UserService.DoSomething() called.");
}
}
public interface IOrderService
{
void ProcessOrder();
}
[ServiceType(ServiceLifetime.Transient)]
public class OrderService: IOrderService
{
public void ProcessOrder()
{
Console.WriteLine("OrderService.ProcessOrder() called.");
}
}
public class Program
{
public static void Main(string[] args)
{
// 创建 ServiceCollection
IServiceCollection services = new ServiceCollection();
// 注册服务
services.RegisterServices("Service", "I");
// 添加其他必要的服务,例如 MVC
services.AddMvc(); // 如果是 ASP.NET Core MVC 项目
// 构建 ServiceProvider
IServiceProvider serviceProvider = services.BuildServiceProvider();
// 从 ServiceProvider 中获取服务并使用
var userService = serviceProvider.GetService<IUserService>();
userService?.DoSomething();
var orderService = serviceProvider.GetService<IOrderService>();
orderService?.ProcessOrder();
Console.ReadKey();
}
}