Skip to content

#如何注册

方案一

将以下的代码放在和Service 层的代码相同的类库中

C
using System.Reflection;

namespace WebApplication1.Service.Base
{
    public static  class ServiceExtensions
    {  
        public static IServiceCollection AddApplicationServices(this IServiceCollection services)
        {
            var assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集

            // 查找所有以 "Service" 结尾且非抽象的类
            var serviceTypes = assembly.GetTypes()
                .Where(t => t.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase))
                .Where(t => !t.IsAbstract && !t.IsInterface);

            foreach (var type in serviceTypes)
            {
                // 获取该类实现的所有接口(通常是单个业务接口)
                var interfaces = type.GetInterfaces();

                // 如果有接口,则按接口注册;否则按自身类型注册
                if (interfaces.Any())
                {
                    foreach (var iface in interfaces)
                    {
                        services.AddScoped(iface, type);
                    }
                }
                else
                {
                    services.AddScoped(type);
                }
            }

            return services;
        }
    }
}

方案二

C
public static class ServiceExtensions
{  
    public static IServiceCollection AddApplicationServices(this IServiceCollection services)
    {
        // 显式加载Serivice类库的程序集
        var serviceAssembly = Assembly.Load("Serivice"); // 通过程序集名称加载
        
        // 或者使用类库中的某个类型来获取程序集(更安全)
        // var serviceAssembly = typeof(ServiceClassInSerivice).Assembly;
        
        // 查找所有以 "Service" 结尾且非抽象的类
        var serviceTypes = serviceAssembly.GetTypes()
            .Where(t => t.Name.EndsWith("Service", StringComparison.OrdinalIgnoreCase))
            .Where(t => !t.IsAbstract && !t.IsInterface);

        foreach (var type in serviceTypes)
        {
            // 获取该类实现的所有接口
            var interfaces = type.GetInterfaces();

            if (interfaces.Any())
            {
                foreach (var iface in interfaces)
                {
                    services.AddScoped(iface, type);
                }
            }
            else
            {
                services.AddScoped(type);
            }
        }

        return services;
    }
}