广州网站建设公司排名,网站建设湖北,百度关键词搜索优化,建设集团企业网站toString方法等。这不仅提高了开发效率#xff0c;还减少了代码中的冗余#xff0c;使代码更加简洁和易于维护。然而#xff0c;在.NET生态系统中#xff0c;虽然没有直接等价于Lombok的官方库#xff0c;但我们可以通过Roslyn源代码生成器来实现类似甚至更强大的功能。本…toString方法等。这不仅提高了开发效率还减少了代码中的冗余使代码更加简洁和易于维护。然而在.NET生态系统中虽然没有直接等价于Lombok的官方库但我们可以通过Roslyn源代码生成器来实现类似甚至更强大的功能。本文将介绍如何在.NET平台上构建一个类似Lombok的代码生成工具实现构造函数注入、日志注入、构造者模式等代码生成功能。为什么需要类似Lombok的工具在现代软件开发中我们经常需要编写大量重复的样板代码例如依赖注入为服务类编写构造函数注入代码数据传输对象(DTO)为实体类创建对应的DTO类Builder模式为复杂对象创建Builder构建器属性访问器为私有字段生成公共属性映射方法在不同对象之间进行属性映射这些样板代码不仅占用大量时间编写还容易出错且难以维护。通过代码生成工具我们可以自动化这些重复性工作让开发者专注于业务逻辑的实现。Mud代码生成器Mud代码生成器是一套基于Roslyn的源代码生成器专门针对.NET平台设计提供了类似Lombok的功能甚至更加丰富。它包含两个主要组件Mud.EntityCodeGenerator实体代码生成器用于根据实体类自动生成各种相关代码Mud.ServiceCodeGenerator服务代码生成器用于自动生成服务层相关代码这套工具通过在代码中添加特定的特性(Attribute)标记然后在编译时自动生成相应的代码大大减少了开发者需要手动编写的代码量。核心功能1. 生成构造函数注入代码在.NET的依赖注入系统中构造函数注入是最推荐的依赖注入方式。然而手动编写构造函数注入代码可能会很繁琐特别是当一个类需要注入多个服务时。Mud.ServiceCodeGenerator提供了多种注入特性可以自动生成构造函数注入代码ConstructorInjectAttribute 字段注入使用[ConstructorInject]特性可以将类中已存在的私有只读字段通过构造函数注入初始化[ConstructorInject]public partial class UserService{private readonly IUserRepository _userRepository;private readonly IRoleRepository _roleRepository;// 生成的代码将包含:// public UserService(IUserRepository userRepository, IRoleRepository roleRepository)// {// _userRepository userRepository;// _roleRepository roleRepository;// }}LoggerInjectAttribute 日志注入使用[LoggerInject]特性可以为类注入ILogger类型的日志记录器[LoggerInject]public partial class UserService{// 生成的代码将包含:// private readonly ILoggerUserService _logger;//// public UserService(ILoggerFactory loggerFactory)// {// _logger loggerFactory.CreateLoggerUserService();// }}CacheInjectAttribute 缓存管理器注入使用[CacheInject]特性可以注入缓存管理器实例[CacheInject]public partial class UserService{// 生成的代码将包含:// private readonly ICacheManager _cacheManager;//// public UserService(ICacheManager cacheManager)// {// _cacheManager cacheManager;// }}UserInjectAttribute 用户管理器注入使用[UserInject]特性可以注入用户管理器实例[UserInject]public partial class UserService{// 生成的代码将包含:// private readonly IUserManager _userManager;//// public UserService(IUserManager userManager)// {// _userManager userManager;// }}OptionsInjectAttribute 配置项注入使用[OptionsInject]特性可以根据指定的配置项类型注入配置实例[OptionsInject(OptionType TenantOptions)]public partial class UserService{// 生成的代码将包含:// private readonly TenantOptions _tenantOptions;//// public UserService(IOptionsTenantOptions tenantOptions)// {// _tenantOptions tenantOptions.Value;// }}CustomInjectAttribute 自定义注入使用[CustomInject]特性可以注入任意类型的依赖项[CustomInject(VarType IRepositorySysUser, VarName _userRepository)][CustomInject(VarType INotificationService, VarName _notificationService)]public partial class UserService{// 生成的代码将包含:// private readonly IRepositorySysUser _userRepository;// private readonly INotificationService _notificationService;//// public UserService(IRepositorySysUser userRepository, INotificationService notificationService)// {// _userRepository userRepository;// _notificationService notificationService;// }}组合注入示例多种注入特性可以组合使用生成器会自动合并所有注入需求[ConstructorInject][LoggerInject][CacheInject][UserInject][OptionsInject(OptionType TenantOptions)][CustomInject(VarType IRepositorySysUser, VarName _userRepository)]public partial class UserService{private readonly IRoleRepository _roleRepository;private readonly IPermissionRepository _permissionRepository;// 生成的代码将包含所有注入项:// private readonly ILoggerUserService _logger;// private readonly ICacheManager _cacheManager;// private readonly IUserManager _userManager;// private readonly TenantOptions _tenantOptions;// private readonly IRepositorySysUser _userRepository;// private readonly IRoleRepository _roleRepository;// private readonly IPermissionRepository _permissionRepository;//// public UserService(// ILoggerFactory loggerFactory,// ICacheManager cacheManager,// IUserManager userManager,// IOptionsTenantOptions tenantOptions,// IRepositorySysUser userRepository,// IRoleRepository roleRepository,// IPermissionRepository permissionRepository)// {// _logger loggerFactory.CreateLoggerUserService();// _cacheManager cacheManager;// _userManager userManager;// _tenantOptions tenantOptions.Value;// _userRepository userRepository;// _roleRepository roleRepository;// _permissionRepository permissionRepository;// }}2. Builder模式代码生成Builder模式是一种创建型设计模式能够分步骤创建复杂对象。使用Builder模式可以创建不同表现的对象同时避免构造函数参数过多的问题。Mud.EntityCodeGenerator支持通过[Builder]特性自动生成Builder构建器模式代码/// summary/// 客户端信息实体类/// /summary[DtoGenerator][Builder][Table(Name sys_client),SuppressSniffer]public partial class SysClientEntity{/// summary/// id/// /summary[property: Column(Name id, IsPrimary true, Position 1)][property: Required(ErrorMessage id不能为空)]private long? _id;/// summary/// 客户端key/// /summary[property: Column(Name client_key, Position 3)][property: Required(ErrorMessage 客户端key不能为空)]private string _clientKey;/// summary/// 删除标志0代表存在 2代表删除/// /summary[property: Column(Name del_flag, Position 10)]private string _delFlag;}基于以上实体将自动生成Builder构建器类/// summary/// see crefSysClientEntity/ 的构建者。/// /summarypublic class SysClientEntityBuilder{private SysClientEntity _sysClientEntity new SysClientEntity();/// summary/// 设置 see crefSysClientEntity.Id/ 属性值。/// /summary/// param nameid属性值/param/// returns返回 see crefSysClientEntityBuilder/ 实例/returnspublic SysClientEntityBuilder SetId(long? id){this._sysClientEntity.Id id;return this;}/// summary/// 设置 see crefSysClientEntity.ClientKey/ 属性值。/// /summary/// param nameclientKey属性值/param/// returns返回 see crefSysClientEntityBuilder/ 实例/returnspublic SysClientEntityBuilder SetClientKey(string clientKey){this._sysClientEntity.ClientKey clientKey;return this;}/// summary/// 设置 see crefSysClientEntity.DelFlag/ 属性值。/// /summary/// param namedelFlag属性值/param/// returns返回 see crefSysClientEntityBuilder/ 实例/returnspublic SysClientEntityBuilder SetDelFlag(string delFlag){this._sysClientEntity.DelFlag delFlag;return this;}/// summary/// 构建 see crefSysClientEntity/ 类的实例。/// /summarypublic SysClientEntity Build(){return this._sysClientEntity;}}使用Builder模式可以链式设置实体属性创建实体对象更加方便var client new SysClientEntityBuilder().SetClientKey(client123).SetDelFlag(0).Build();3. DTO/VO代码生成在现代Web应用开发中数据传输对象(DTO)和视图对象(VO)是常见的设计模式。它们用于在不同层之间传输数据避免直接暴露实体类。Mud.EntityCodeGenerator可以自动生成DTO和VO类/// summary/// 客户端信息实体类/// /summary[DtoGenerator][Table(Name sys_client),SuppressSniffer]public partial class SysClientEntity{/// summary/// id/// /summary[property: TableField(Fille FieldFill.Insert, Value FillValue.Id)][property: Column(Name id, IsPrimary true, Position 1)][property: Required(ErrorMessage id不能为空)]private long? _id;/// summary/// 客户端key/// /summary[property: Column(Name client_key, Position 3)][property: Required(ErrorMessage 客户端key不能为空)][property: ExportProperty(客户端key)][property: CustomVo1, CustomVo2][property: CustomBo1, CustomBo2]private string _clientKey;/// summary/// 删除标志0代表存在 2代表删除/// /summary[property: Column(Name del_flag, Position 10)][property: ExportProperty(删除标志)][IgnoreQuery]private string _delFlag;}基于以上实体将自动生成以下几类代码VO类 (视图对象)/// summary/// 客户端信息实体类/// /summary[SuppressSniffer, CompilerGenerated]public partial class SysClientListOutput{/// summary/// id/// /summarypublic long? id { get; set; }/// summary/// 客户端key/// /summary[ExportProperty(客户端key)][CustomVo1, CustomVo2]public string? clientKey { get; set; }/// summary/// 删除标志0代表存在 2代表删除/// /summary[ExportProperty(删除标志)]public string? delFlag { get; set; }}QueryInput类 (查询输入对象)// SysClientQueryInput.g.cs/// summary/// 客户端信息实体类/// /summary[SuppressSniffer, CompilerGenerated]public partial class SysClientQueryInput : DataQueryInput{/// summary/// id/// /summarypublic long? id { get; set; }/// summary/// 客户端key/// /summarypublic string? clientKey { get; set; }/// summary/// 删除标志0代表存在 2代表删除/// /summarypublic string? delFlag { get; set; }/// summary/// 构建通用的查询条件。/// /summarypublic ExpressionFuncSysClientEntity, bool BuildQueryWhere(){var where LinqExtensions.TrueSysClientEntity();where where.AndIF(this.id ! null, x x.Id this.id);where where.AndIF(!string.IsNullOrEmpty(this.clientKey), x x.ClientKey this.clientKey);where where.AndIF(!string.IsNullOrEmpty(this.delFlag), x x.DelFlag this.delFlag);return where;}}CrInput类 (创建输入对象)// SysClientCrInput.g.cs/// summary/// 客户端信息实体类/// /summary[SuppressSniffer, CompilerGenerated]public partial class SysClientCrInput{/// summary/// 客户端key/// /summary[Required(ErrorMessage 客户端key不能为空), CustomBo1, CustomBo2]public string? clientKey { get; set; }/// summary/// 删除标志0代表存在 2代表删除/// /summarypublic string? delFlag { get; set; }/// summary/// 通用的BO对象映射至实体方法。/// /summarypublic virtual SysClientEntity MapTo(){var entity new SysClientEntity();entity.ClientKey this.clientKey;entity.DelFlag this.delFlag;return entity;}}UpInput类 (更新输入对象)/// summary/// 客户端信息实体类/// /summary[SuppressSniffer, CompilerGenerated]public partial class SysClientUpInput : SysClientCrInput{/// summary/// id/// /summary[Required(ErrorMessage id不能为空)]public long? id { get; set; }/// summary/// 通用的BO对象映射至实体方法。/// /summarypublic override SysClientEntity MapTo(){var entity base.MapTo();entity.Id this.id;return entity;}}4. 实体映射方法生成在不同对象之间进行属性映射是一项常见但繁琐的工作。Mud.EntityCodeGenerator可以自动生成实体与DTO之间的映射方法/// summary/// 通用的实体映射至VO对象方法。/// /summarypublic virtual SysClientListOutput MapTo(){var voObj new SysClientListOutput();voObj.id this.Id;voObj.clientKey this.ClientKey;voObj.delFlag this.DelFlag;return voObj;}配置和使用项目配置在使用Mud代码生成器时可以通过在项目文件中配置参数来自定义生成行为。实体代码生成器配置参数PropertyGroupEmitCompilerGeneratedFilestrue/EmitCompilerGeneratedFiles !-- 在obj目录下保存生成的代码 --EntitySuffixEntity/EntitySuffix !-- 实体类后缀配置 --EntityAttachAttributesSuppressSniffer/EntityAttachAttributes !-- 生成的VO、BO类加上Attribute特性配置多个特性时使用,分隔 --!-- 属性名配置 --PropertyNameLowerCaseFirstLettertrue/PropertyNameLowerCaseFirstLetter !-- 是否将生成的属性名首字母小写默认为true --!-- VO/BO 属性配置参数 --VoAttributesCustomVo1Attribute,CustomVo2Attribute/VoAttributes !-- 需要添加至VO类的自定义特性多个特性时使用,分隔 --BoAttributesCustomBo1Attribute,CustomBo2Attribute/BoAttributes !-- 需要添加至BO类的自定义特性多个特性时使用,分隔 --/PropertyGroupItemGroupCompilerVisibleProperty IncludeEntitySuffix /CompilerVisibleProperty IncludeEntityAttachAttributes /CompilerVisibleProperty IncludePropertyNameLowerCaseFirstLetter /CompilerVisibleProperty IncludeVoAttributes /CompilerVisibleProperty IncludeBoAttributes //ItemGroup服务代码生成器配置参数PropertyGroupEmitCompilerGeneratedFilestrue/EmitCompilerGeneratedFiles !-- 在obj目录下保存生成的代码 --!-- 依赖注入相关配置 --DefaultCacheManagerTypeICacheManager/DefaultCacheManagerType !-- 缓存管理器类型默认值 --DefaultUserManagerTypeIUserManager/DefaultUserManagerType !-- 用户管理器类型默认值 --DefaultLoggerVariable_logger/DefaultLoggerVariable !-- 日志变量名默认值 --DefaultCacheManagerVariable_cacheManager/DefaultCacheManagerVariable !-- 缓存管理器变量名默认值 --DefaultUserManagerVariable_userManager/DefaultUserManagerVariable !-- 用户管理器变量名默认值 --!-- 服务生成相关配置 --ServiceGeneratortrue/ServiceGenerator !-- 是否生成服务端代码 --EntitySuffixEntity/EntitySuffix !-- 实体类后缀配置 --ImpAssemblyMud.System/ImpAssembly !-- 需要生成代码的接口实现程序集 --!-- DTO生成相关配置 --EntityAttachAttributesSuppressSniffer/EntityAttachAttributes !-- 实体类加上Attribute特性配置多个特性时使用,分隔 --/PropertyGroupItemGroupCompilerVisibleProperty IncludeDefaultCacheManagerType /CompilerVisibleProperty IncludeDefaultUserManagerType /CompilerVisibleProperty IncludeDefaultLoggerVariable /CompilerVisibleProperty IncludeDefaultCacheManagerVariable /CompilerVisibleProperty IncludeDefaultUserManagerVariable /CompilerVisibleProperty IncludeServiceGenerator /CompilerVisibleProperty IncludeEntitySuffix /CompilerVisibleProperty IncludeImpAssembly /CompilerVisibleProperty IncludeEntityAttachAttributes //ItemGroup依赖项配置ItemGroup!-- 引入的代码生成器程序集 --PackageReference IncludeMud.EntityCodeGenerator Version1.1.8 /PackageReference IncludeMud.ServiceCodeGenerator Version1.1.8 //ItemGroup高级特性忽略字段注入对于某些不需要通过构造函数注入的字段可以使用[IgnoreGenerator]特性标记[ConstructorInject]public partial class UserService{private readonly IUserRepository _userRepository;[IgnoreGenerator]private readonly string _connectionString default_connection_string; // 不会被注入// 只有_userRepository会被构造函数注入}自定义属性生成Mud代码生成器支持通过配置参数为生成的类添加自定义特性PropertyGroup!-- 需要添加至VO类的自定义特性多个特性时使用,分隔 --VoAttributesCustomVo1Attribute,CustomVo2Attribute/VoAttributes!-- 需要添加至BO类的自定义特性多个特性时使用,分隔 --BoAttributesCustomBo1Attribute,CustomBo2Attribute/BoAttributes/PropertyGroup与其他工具的比较与AutoMapper的比较AutoMapper是一个流行的对象映射工具但它运行时进行映射而Mud代码生成器在编译时生成映射代码。这意味着性能Mud生成的代码在运行时性能更好因为没有反射开销类型安全编译时生成的代码具有更好的类型安全性调试友好生成的代码可以直接调试更容易排查问题与传统手工编码的比较开发效率大大减少了样板代码的编写时间维护性当实体类发生变化时相关代码会自动更新一致性生成的代码风格统一减少了人为错误最佳实践1. 合理使用特性标记不要为所有类都添加代码生成特性只在确实需要的类上使用。过度使用可能导致生成大量不必要的代码。2. 配置参数优化根据项目实际情况配置生成参数例如PropertyGroupEmitCompilerGeneratedFilestrue/EmitCompilerGeneratedFilesEntitySuffixEntity/EntitySuffixPropertyNameLowerCaseFirstLetterfalse/PropertyNameLowerCaseFirstLetter/PropertyGroup3. 查看生成代码在开发阶段建议启用[EmitCompilerGeneratedFiles]参数以便查看生成的代码PropertyGroupEmitCompilerGeneratedFilestrue/EmitCompilerGeneratedFiles/PropertyGroup生成的代码将位于obj/[Configuration]/[TargetFramework]/generated/目录下文件名以.g.cs结尾。4. 版本管理生成的代码不需要加入版本管理因为它们会在编译时自动生成。可以在.gitignore中添加**/*.g.cs实际应用案例案例1用户服务类[ConstructorInject][LoggerInject][CacheInject][UserInject]public partial class UserService{private readonly IUserRepository _userRepository;private readonly IRoleRepository _roleRepository;public async TaskUserDto GetUserAsync(long userId){_logger.LogInformation(Getting user with id: {UserId}, userId);var user await _userRepository.GetByIdAsync(userId);if (user null){_logger.LogWarning(User with id {UserId} not found, userId);return null;}var userDto user.MapTo();return userDto;}}案例2订单实体类[DtoGenerator][Builder]public partial class OrderEntity{[property: Column(Name id, IsPrimary true)][property: Required]private long? _id;[property: Column(Name order_no)][property: Required]private string _orderNo;[property: Column(Name amount)][property: Required]private decimal? _amount;[property: Column(Name status)]private string _status;}性能和安全性考虑性能优势编译时生成所有代码在编译时生成运行时无额外开销无反射调用生成的代码直接调用避免反射带来的性能损耗类型安全编译时检查确保类型安全减少运行时错误安全性考虑代码审查虽然代码是自动生成的但仍需要审查生成的代码以确保符合安全要求依赖注入通过构造函数注入确保依赖关系明确便于测试和维护访问控制生成的属性和方法遵循.NET的访问控制原则扩展和定制Mud代码生成器设计为可扩展的开发者可以根据自己的需求定制代码生成逻辑自定义特性可以创建自己的特性来控制代码生成行为模板定制可以修改代码生成模板以适应特定需求插件机制可以通过插件机制添加新的代码生成功能总结通过Mud代码生成器我们可以在.NET平台上实现类似Java Lombok的功能甚至更加丰富和强大。这套工具通过Roslyn源代码生成技术在编译时自动生成我们需要的样板代码大大提高了开发效率减少了手动编写代码的工作量。主要优势包括提高开发效率自动生成构造函数注入、Builder模式、DTO等代码保证代码质量生成的代码遵循统一规范减少人为错误提升性能编译时生成运行时无额外开销易于维护当源代码变化时相关代码自动更新通过合理使用这套工具我们可以专注于业务逻辑的实现而将重复性的样板代码交给代码生成器处理真正实现高效、高质量的软件开发。无论你是正在开发新的.NET项目还是想要重构现有项目以减少样板代码Mud代码生成器都是一个值得考虑的强大工具。它不仅能够显著提高开发效率还能帮助团队保持代码的一致性和可维护性。开始使用Mud代码生成器让你的.NET开发体验更加接近Java Lombok带来的便利甚至更进一步分类: .net标签: .net, c#, Roslyn, 代码生成好文要顶 关注我 收藏该文 微信分享玩泥巴的|mudtools.cn粉丝 - 8 关注 - 1加关注811升级成为会员« 上一篇 .NET驾驭Word之力数据驱动文档 - 邮件合并与自定义数据填充完全指南» 下一篇 .NET驾驭Word之力基于规则自动生成及排版Word文档posted 2025-10-10 09:21 玩泥巴的|mudtools.cn 阅读(1626) 评论(15) 收藏 举报刷新页面返回顶部登录后才能查看或发表评论立即 登录 或者 逛逛 博客园首页【推荐】注册成为HarmonyOS开发者支持博客园HarmonyOS社区建设【推荐】英博云GPU容器服务平台智能算力即开即用立即免费试用【推荐】科研领域的连接者艾思科蓝一站式科研学术服务数字化平台【推荐】诚邀您体验阿里巴巴推出的新一代 Agentic 编程平台 Qoder编辑推荐OpenCVSharp了解几种特征检测Keepalived详解原理、编译安装与高可用集群配置生产事故-那些年遇到过的OOMAvalonia 实现跨平台的视频会议Windows、Linux、信创Elasticsearch 避坑指南我在项目中总结的 14 条实用经验鸿蒙专区CodeGenie 基于图片生成鸿蒙应用UI代码生态市场全新升级助力鸿蒙应用高效开发鸿蒙新闻行业解决方案助力行业应用体验变革揭秘长相思App如何在鸿蒙打造沉浸式阅读体验独立开发者冲在「改变世界」第一线公告昵称 玩泥巴的|mudtools.cn园龄 5年11个月粉丝 8关注 1加关注 2025年12月 日 一 二 三 四 五 六30 1 2 3 4 5 67 8 9 10 11 12 1314 15 16 17 18 19 2021 22 23 24 25 26 2728 29 30 31 1 2 34 5 6 7 8 9 10搜索常用链接我的随笔我的评论我的参与最新评论我的标签我的标签二次开发(14)c#(11).net(11)COM互操作(10)Word(8)Office(7)Roslyn(4)Excel(4)飞书(4)代码生成(4)随笔分类.net(5)Office二次开发(10)飞书二次开发(3)随笔档案2025年12月(2)2025年11月(5)2025年10月(3)2025年9月(8)2025年8月(3)阅读排行榜1. 打造.NET平台的Lombok实现构造函数注入、日志注入、构造者模式代码生成等功能(1626)2. 不一样的.NET烟火基于Roslyn的开源代码生成器(1507)3. 开源一套.NET平台的Excel COM 组件二次封装库(1212)4. .NET驾驭Word之力基于规则自动生成及排版Word文档(1173)5. .NET操作Word/WPS打造专业文档 - 页面设置与打印控制完全指南(565)评论排行榜1. 打造.NET平台的Lombok实现构造函数注入、日志注入、构造者模式代码生成等功能(15)2. .NET驾驭Word之力基于规则自动生成及排版Word文档(9)3. 开源一套.NET平台的Excel COM 组件二次封装库(9)4. 不一样的.NET烟火基于Roslyn的开源代码生成器(6)5. .NET项目中如何快速的集成飞书API(5)推荐排行榜1. .NET项目中如何快速的集成飞书API(8)2. .NET驾驭Word之力基于规则自动生成及排版Word文档(8)3. 打造.NET平台的Lombok实现构造函数注入、日志注入、构造者模式代码生成等功能(8)4. 不一样的.NET烟火基于Roslyn的开源代码生成器(8)5. 开源一套.NET平台的Excel COM 组件二次封装库(6)最新评论1. Re:一分钟实现.NET与飞书长连接的WebSocket架构支持支持为壮大c#添砖加瓦--三合视角2. Re:.NET项目中如何快速的集成飞书API可以啊这是收藏了--三合视角3. Re:.NET项目中如何快速的集成飞书API云游工坊 OK...--玩泥巴的|mudtools.cn4. Re:.NET项目中如何快速的集成飞书API玩泥巴的|mudtools.cn 我说的是长连接...--云游工坊5. Re:.NET项目中如何快速的集成飞书API云游工坊 就是看到官方没.net版本所以才做的。...