在ASP.NET Core中使用Scrutor注册与解析领域服务
改用Scrutor批量注册领域服务的实现步骤
问题背景
已定义根领域服务接口IDomainService,以及多个继承它的子接口(如IProductionLineTitleDuplicationChecker),对应实现类遵循“接口名去掉前缀I即为实现类名”的命名规则。现需替换ASP.NET Core内置DI,用Scrutor完成批量注册。
实现步骤
1. 安装Scrutor包
通过NuGet安装Scrutor:
Install-Package Scrutor # 或使用.NET CLI dotnet add package Scrutor
2. 在Program.cs中配置服务注册
在ASP.NET Core启动配置文件(Program.cs)中,使用Scrutor的Scan扩展方法批量扫描并注册所有领域服务:
var builder = WebApplication.CreateBuilder(args); // 其他服务配置... // Scrutor批量注册领域服务逻辑 builder.Services.Scan(scan => scan // 扫描IDomainService所在的程序集,自动覆盖所有关联实现类 .FromAssemblyOf<IDomainService>() // 筛选所有继承自IDomainService的非抽象类 .AddClasses(classes => classes .Where(type => type.IsClass && !type.IsAbstract && type.GetInterfaces().Any(i => i.IsAssignableTo<IDomainService>()))) // 自动匹配命名对应的接口(如ProductionLineTitleDuplicationChecker → IProductionLineTitleDuplicationChecker) .AsMatchingInterface() // 设置服务生命周期为Scoped,可按需替换为WithSingletonLifetime/WithTransientLifetime .WithScopedLifetime()); var app = builder.Build(); // 中间件配置... app.Run();
关键说明
FromAssemblyOf<IDomainService>:指定扫描范围为包含根接口的程序集,确保所有领域服务实现类都被覆盖。AsMatchingInterface:严格遵循“类名=接口名去掉前缀I”的命名规则,精准注册子接口与实现类的对应关系。- 生命周期:根据业务场景选择合适的生命周期,
Scoped是Web应用中最常用的选项。
使用验证
在需要调用领域服务的类中,直接注入对应子接口即可,DI容器会自动解析到实现类:
public class ProductionLineController : ControllerBase { private readonly IProductionLineTitleDuplicationChecker _duplicationChecker; public ProductionLineController(IProductionLineTitleDuplicationChecker duplicationChecker) { _duplicationChecker = duplicationChecker; } // 业务方法中调用_duplicationChecker.IsDuplicated(...) }
内容的提问来源于stack exchange,提问作者HassanJalali
相关产品推荐
相关产品推荐

