怪奇物语

怪奇物语

首页 新随笔 联系 管理

手动批量注入service 自动依赖注入 C# asp.net dontet 依赖注入

public static class ServiceCollectionExtensions
{

    // 批量注入所有的继承IBaseService的Service
    public static void AddPDAServices(this IServiceCollection services)
    {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();

        foreach (var assembly in assemblies)
        {
            //获取继承IBaseAppService的类
            List<Type> types = assembly.GetTypes().Where(t => t.IsClass && t.GetInterfaces().Contains(typeof(IBaseAppService))).ToList();

            types.ForEach(impl =>
            {
                //获取该类所继承的所有接口
                Type[] interfaces = impl.GetInterfaces();
                interfaces
                    .ToList()
                    .ForEach(i =>
                    {
                        services.AddScoped(i, impl);
                    });
            });
        }
    }
}
posted on 2024-11-30 08:00  超级无敌美少男战士  阅读(30)  评论(0)    收藏  举报