CloudBuilder/CloudBuilder.Core/DependencyInjection/Task/ScheduleTaskPack.cs
owenchen 1c0c83af5f ow
2026-05-12 10:09:31 +08:00

57 lines
2.1 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using CloudBuilder.Core.Application.Builders;
using CloudBuilder.Core.Application.Packs;
using CloudBuilder.Core.Extensions;
using CloudBuilder.Core.Service;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace CloudBuilder.Core.DependencyInjection.Task
{
[PackLevel(20)]
public class ScheduleTaskPack : CloudBuilderPack
{
/// <summary>
/// 获取 模块级别
/// </summary>
public override PackLevel Level => PackLevel.Business;
/// <summary>
/// 获取 模块启动顺序,模块启动的顺序先按级别启动,级别内部再按此顺序启动
/// </summary>
public override int Order => 2;
/// <summary>
/// 将服务添加到依赖注入服务容器中
/// </summary>
/// <param name="services">依赖注入服务容器</param>
/// <returns></returns>
public override IServiceCollection AddServices(IServiceCollection services, CloudBuilderBuilder builder)
{
var baseType = typeof(IScheduleTask);
var allAssemblies = CloudBuilderBuilder.GetAssemblies();
var types = allAssemblies
.SelectMany(a => a.DefinedTypes)
.Select(type => type.AsType())
.Where(type => type != baseType && type.HasImplementedRawGeneric(baseType))
.Where(x => x.IsClass).ToList();
foreach (var implementType in types)
{
//使用TryAddScoped可以避免同一个接口注册多个实现
//使用AddScoped可以同一个接口注册多个实现
//即使容器中原本就有IOrder服务也会再添加一个IOrder服务进去这样一来容器中就会存在多个IOrder服务
//在需要获取服务的地方注入IOrder服务时默认会得到最后一个注册的IOrder服务实例
//IEnumerable<IOrder> orders获取所有的IOrder服务
services.AddScoped(baseType, implementType);
}
return services;
}
}
}