Util 应用框架安装与配置指南
概述
Util 是一个 .NET 平台下的应用框架,旨在提升中小团队的开发能力。它由工具类、分层架构基类、UI组件、配套代码生成模板、权限管理等组成。本文将从零开始详细介绍 Util 框架的安装与配置过程。
环境要求
在开始安装 Util 框架之前,请确保您的开发环境满足以下要求:
| 组件 | 版本要求 | 说明 |
|---|---|---|
| .NET SDK | 8.0+ | Util 框架基于 .NET 8.0 构建 |
| IDE | Visual Studio 2022+ 或 Rider | 推荐使用最新版本的开发工具 |
| 数据库 | SQL Server/MySQL/PostgreSQL | 支持多种主流数据库 |
安装方式
Util 框架提供多种安装方式,您可以根据项目需求选择合适的方式:
1. NuGet 包安装(推荐)
Util 框架通过 NuGet 包分发,您可以通过以下命令安装核心包:
# 安装核心工具包
dotnet add package Util.Core
# 安装数据访问层(Entity Framework Core)
dotnet add package Util.Data.EntityFrameworkCore
# 安装应用层
dotnet add package Util.Application
# 安装 Web API 支持
dotnet add package Util.Application.WebApi
# 安装 ASP.NET Core 集成
dotnet add package Util.AspNetCore
2. 项目引用安装
如果您需要修改框架源码或进行深度定制,可以通过项目引用的方式安装:
<!-- 在 .csproj 文件中添加项目引用 -->
<ItemGroup>
<ProjectReference Include="..\Util.Core\01-Util.Core.csproj" />
<ProjectReference Include="..\Util.Data.EntityFrameworkCore\05-Util.Data.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\Util.Application\01-Util.Application.csproj" />
</ItemGroup>
项目配置
1. 创建项目结构
Util 框架采用分层架构设计,建议按照以下结构组织项目:
2. 配置启动类
在 Startup.cs 或 Program.cs 中配置 Util 框架:
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Util.Data.EntityFrameworkCore;
using Util.AspNetCore;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// 添加 Util 框架服务
services.AddUtil();
// 配置数据库上下文
services.AddSqlServerUnitOfWork<IMyUnitOfWork, MyUnitOfWork>(
Configuration.GetConnectionString("DefaultConnection"));
// 添加控制器
services.AddControllers();
// 添加 Swagger
services.AddSwaggerGen();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
// 使用 Util 中间件
app.UseUtil();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
// 使用 Swagger
app.UseSwagger();
app.UseSwaggerUI();
}
}
3. 配置文件设置
在 appsettings.json 中配置数据库连接和其他设置:
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyAppDb;Trusted_Connection=true;TrustServerCertificate=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Util": "Information"
}
},
"AllowedHosts": "*"
}
数据库配置
1. 创建数据库上下文
using Util.Data.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
public interface IMyUnitOfWork : IUnitOfWork
{
DbSet<User> Users { get; }
DbSet<Role> Roles { get; }
}
public class MyUnitOfWork : DbContext, IMyUnitOfWork
{
public MyUnitOfWork(DbContextOptions<MyUnitOfWork> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// 配置实体映射
modelBuilder.ApplyConfiguration(new UserConfiguration());
modelBuilder.ApplyConfiguration(new RoleConfiguration());
}
}
2. 实体配置示例
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Util.Domain;
public class User : AggregateRoot<User>
{
public string Name { get; set; }
public string Email { get; set; }
public string PasswordHash { get; set; }
}
public class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable("Users");
builder.Property(t => t.Name).HasMaxLength(100).IsRequired();
builder.Property(t => t.Email).HasMaxLength(200).IsRequired();
builder.Property(t => t.PasswordHash).HasMaxLength(500).IsRequired();
// 添加索引
builder.HasIndex(t => t.Email).IsUnique();
}
}
依赖注入配置
Util 框架自动处理大部分依赖注入配置,您只需要关注业务相关的服务注册:
// 在启动类中注册服务
services.AddScoped<IUserService, UserService>();
services.AddScoped<IRoleService, RoleService>();
// 或者使用 Util 的自动注册功能
// 实现 IScopeDependency 接口的服务会自动注册为 Scoped 生命周期
public class UserService : IScopeDependency
{
private readonly IRepository<User> _userRepository;
public UserService(IRepository<User> userRepository)
{
_userRepository = userRepository;
}
public async Task<User> GetUserAsync(Guid id)
{
return await _userRepository.FindAsync(id);
}
}
常用配置选项
Util 框架提供了丰富的配置选项,以下是一些常用配置:
1. 缓存配置
services.AddEasyCaching(options =>
{
options.UseInMemory("default");
// 或者使用 Redis
// options.UseRedis(config =>
// {
// config.DBConfig.Endpoints.Add(new ServerEndPoint("localhost", 6379));
// }, "default");
});
2. 日志配置
services.AddSerilog((context, configuration) =>
{
configuration
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day);
});
3. 验证配置
// Util 框架自动集成 DataAnnotations 验证
// 在 DTO 或实体上使用特性进行验证
public class CreateUserDto
{
[Required(ErrorMessage = "用户名不能为空")]
[StringLength(100, ErrorMessage = "用户名长度不能超过100个字符")]
public string Name { get; set; }
[Required(ErrorMessage = "邮箱不能为空")]
[EmailAddress(ErrorMessage = "邮箱格式不正确")]
public string Email { get; set; }
}
开发工作流
Util 框架推荐以下开发工作流:
常见问题解决
1. 数据库迁移问题
# 创建迁移
dotnet ef migrations add InitialCreate --context MyUnitOfWork
# 应用迁移
dotnet ef database update --context MyUnitOfWork
2. 依赖注入错误
如果遇到依赖注入错误,检查服务是否实现了正确的接口:
ISingletonDependency- 单例服务IScopeDependency- 作用域服务ITransientDependency- 瞬时服务
3. 配置错误
确保在 appsettings.json 中正确配置了数据库连接字符串和其他必要设置。
性能优化建议
| 优化点 | 建议配置 | 说明 |
|---|---|---|
| 数据库连接池 | MaxPoolSize=100 | 根据实际负载调整连接池大小 |
| 缓存策略 | 内存缓存 + Redis | 分层缓存提高性能 |
| 日志级别 | Production环境设为Warning | 减少日志输出提升性能 |
| EF Core配置 | UseQuerySplittingBehavior | 优化查询性能 |
总结
Util 框架提供了一个完整的企业级应用开发解决方案,通过合理的安装和配置,您可以快速搭建健壮的应用程序。本文详细介绍了从环境准备到具体配置的完整流程,帮助您顺利开始 Util 框架的开发之旅。
记住框架的设计理念:简单易用,尽量少的配置,不用精确记忆 API,有个模糊印象即可使用。对于有 .NET 基础的开发人员,通常在 3 天内就能上手 Util 框架。
开始您的 Util 框架之旅吧!
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



