Smart.App
5.0.2
See the version list below for details.
dotnet new install Smart.App::5.0.2
Smart.App
基于 DDD(领域驱动设计)架构的现代化 .NET 控制台应用快速开发框架,为开发者提供开箱即用的企业级解决方案。
📖 简介
Smart.App 是一个功能强大的 .NET 控制台应用模板,采用领域驱动设计(DDD)架构模式,基于 Microsoft.Extensions.Hosting 构建。该模板集成了依赖注入、配置管理、后台服务、日志记录等企业级功能,帮助开发者快速构建可维护、可扩展的控制台应用程序。
核心特性
- 🏗️ DDD 架构设计 - 完整的领域驱动设计分层架构
- 🔧 自动依赖注入 - 基于 Smart.Inject 的服务自动扫描与注册
- 🚀 后台服务支持 - 原生支持 IHostedService 后台服务
- 📝 企业级日志 - 集成 NLog 日志框架
- ⚙️ 多环境配置 - 支持 Development、Staging、Production 多环境配置
- 🛡️ 优雅停机 - 完善的 Ctrl+C 中断处理机制
- 🌐 跨平台支持 - 完美支持 Windows、Linux、macOS
- 📦 丰富的中间件集成 - 内置 MailKit、Redis、PostgreSQL、RabbitMQ 支持
- 🎯 中文编码支持 - 原生支持 GBK/GB2312 等中文编码
🎯 功能特性
1. DDD 分层架构
项目采用标准的 DDD 分层架构,清晰划分职责:
Smart.App/
├── Smart.App.Domain/ # 领域层 - 核心业务逻辑
│ ├── Entities/ # 实体
│ └── Interfaces/ # 领域接口
├── Smart.App.Application/ # 应用层 - 应用服务
│ ├── BackgroundServices/ # 后台服务
│ └── Services/ # 应用服务
└── Smart.App.Infrastructure/ # 基础设施层 - 技术实现
├── Configuration/ # 配置管理
└── Data/ # 数据访问
2. 现代化控制台架构
基于 Microsoft.Extensions.Hosting 构建,提供:
- 后台服务支持 - 通过
BackgroundService实现长时间运行的后台任务 - 优雅停机机制 - 完善的 Ctrl+C 中断处理和资源清理
- 环境感知配置 - 根据运行环境自动加载对应配置文件
3. 自动服务注册
集成 Smart.Inject 框架,支持:
// 通过特性自动注册服务
[Service(ServiceLifetime.Singleton, InjectScheme.OnlySelf)]
public class DataService
{
// 业务逻辑实现
}
// 扫描并注册所有标记的服务
services.ScanRegisterServices(context.Configuration);
4. 企业级配置管理
支持多种配置源,灵活管理应用配置:
builder.ConfigureAppConfiguration((context, config) =>
{
config.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true, true)
.AddEnvironmentVariables();
if (context.HostingEnvironment.IsDevelopment())
{
config.AddUserSecrets<Program>();
}
});
5. 丰富的中间件集成
开箱即用的企业级中间件支持:
- Smart.MailKit - 邮件发送服务
- Smart.StackRedis - Redis 缓存服务
- Smart.Npgsql - PostgreSQL 数据库访问
- Smart.RabbitMQ - 消息队列服务
- Smart.Channel - 高性能通道服务
6. 智能异常处理
根据环境自动调整异常处理策略:
services.Configure<HostOptions>(options =>
{
// 开发环境:异常时停止服务
// 生产环境:忽略异常,保持服务运行
options.BackgroundServiceExceptionBehavior =
context.HostingEnvironment.IsDevelopment()
? BackgroundServiceExceptionBehavior.StopHost
: BackgroundServiceExceptionBehavior.Ignore;
});
🚀 快速开始
安装模板
dotnet new install Smart.App
创建新项目
# 创建 .NET 8 项目
dotnet new smart.app -n MyDemo -f net8.0
# 创建 .NET 10 项目
dotnet new smart.app -n MyDemo -f net10.0
项目结构
创建完成后,项目将包含以下结构:
MyDemo/
├── MyDemo.Domain/ # 领域层
│ ├── Entities/
│ │ └── People.cs
│ └── Interfaces/
│ ├── IRepository.cs
│ └── IPeopleRepository.cs
├── MyDemo.Application/ # 应用层
│ ├── BackgroundServices/
│ │ └── DemoHostedService.cs
│ └── Services/
│ ├── DemoService.cs
│ └── PeopleService.cs
├── MyDemo.Infrastructure/ # 基础设施层
│ ├── Configuration/
│ │ ├── ServiceConfigure.cs
│ │ └── ServiceExtensions.cs
│ └── Data/
│ ├── Repositories/
│ │ └── PeopleRepository.cs
│ └── DbContext.cs
└── MyDemo/ # 启动项目
├── Program.cs
├── appsettings.json
├── appsettings.Development.json
├── appsettings.Staging.json
├── appsettings.Production.json
└── NLog.config
实现后台服务
public class MyHostedService : BackgroundService
{
private readonly ILogger<MyHostedService> _logger;
private readonly IServiceScopeFactory _serviceScopeFactory;
public MyHostedService(ILogger<MyHostedService> logger, IServiceScopeFactory scopeFactory)
{
_logger = logger;
_serviceScopeFactory = scopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation($"{nameof(MyHostedService)} is running!");
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = _serviceScopeFactory.CreateScope();
var myService = scope.ServiceProvider.GetRequiredService<MyService>();
await myService.ExecuteAsync();
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
catch (OperationCanceledException)
{
_logger.LogInformation($"{nameof(MyHostedService)} is canceled.");
}
catch (Exception ex)
{
_logger.LogError(ex, $"{nameof(MyHostedService)} encountered an error.");
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}
}
}
注册应用服务
[Service(ServiceLifetime.Singleton, InjectScheme.OnlySelf)]
public class MyService
{
private readonly ILogger<MyService> _logger;
public MyService(ILogger<MyService> logger)
{
_logger = logger;
}
public async Task ExecuteAsync()
{
_logger.LogInformation("Executing service logic...");
// 业务逻辑实现
}
}
配置中间件
在 ServiceConfigure.cs 中配置所需的中间件:
public void Configure(IServiceCollection services, IConfiguration configuration)
{
// 配置邮件服务
services.AddMailKit(configuration);
// 配置 Redis 缓存
services.AddStackRedis(configuration);
// 配置 PostgreSQL 数据库
services.AddNpgsql(configuration);
// 配置 RabbitMQ 消息队列
services.AddRabbitMQ(configuration);
// 其他配置...
}
📦 部署指南
部署模式要求
重要:本模板必须使用「依赖框架」部署模式
| 部署模式 | 适用场景 | 本模板支持 |
|---|---|---|
| 依赖框架(FDD) | 目标机器已安装 .NET 运行时 | ✅ 强制使用 |
| 独立部署(SCD) | 无运行时环境 | ❌ 不支持 |
发布命令
# .NET 8 发布
dotnet publish -c Release --self-contained false -f net8.0
# .NET 10 发布
dotnet publish -c Release --self-contained false -f net10.0
运行时安装
在部署目标机器上安装对应的 .NET 运行时:
推荐使用 .NET 运行时安装脚本 进行自动化部署。
🛠️ 开发建议
服务注册约定
本模板使用 Smart.Inject 框架进行依赖注入,请参考其文档了解详细用法:
DDD 最佳实践
- 领域层(Domain) - 保持纯净,不依赖任何基础设施
- 应用层(Application) - 编排领域逻辑,处理用例
- 基础设施层(Infrastructure) - 实现技术细节,如数据访问
日志记录
使用 NLog 进行日志记录,配置文件位于 NLog.config:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd">
<targets>
<target name="logfile" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" />
<target name="console" xsi:type="ColoredConsole" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile,console" />
</rules>
</nlog>
配置管理
appsettings.json- 基础配置appsettings.Development.json- 开发环境配置appsettings.Staging.json- 预发布环境配置appsettings.Production.json- 生产环境配置
中文编码支持
模板已内置中文编码支持,可直接使用 GBK/GB2312 编码读写文件:
// 已在 Program.cs 中配置
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
📋 技术栈
| 技术 | 版本 | 说明 |
|---|---|---|
| .NET | 8.0 / 10.0 | 运行时框架 |
| Microsoft.Extensions.Hosting | Latest | 通用主机 |
| Smart.Inject | Latest | 依赖注入框架 |
| NLog | Latest | 日志框架 |
| Smart.MailKit | Latest | 邮件服务 |
| Smart.StackRedis | Latest | Redis 客户端 |
| Smart.Npgsql | Latest | PostgreSQL 客户端 |
| Smart.RabbitMQ | Latest | 消息队列客户端 |
🤝 贡献
欢迎提交 Issue 和 Pull Request 来帮助改进这个项目!
📄 许可证
MIT License
👨💻 作者
Developed by zenglei
Smart.App
A modern .NET console application rapid development framework based on DDD (Domain-Driven Design) architecture, providing enterprise-grade solutions out of the box for developers.
📖 Introduction
Smart.App is a powerful .NET console application template that adopts the Domain-Driven Design (DDD) architectural pattern and is built on Microsoft.Extensions.Hosting. This template integrates enterprise-grade features such as dependency injection, configuration management, background services, and logging, helping developers quickly build maintainable and scalable console applications.
Core Features
- 🏗️ DDD Architecture - Complete domain-driven design layered architecture
- 🔧 Automatic Dependency Injection - Service auto-scanning and registration based on Smart.Inject
- 🚀 Background Service Support - Native support for IHostedService background services
- 📝 Enterprise Logging - Integrated NLog logging framework
- ⚙️ Multi-Environment Configuration - Support for Development, Staging, Production environments
- 🛡️ Graceful Shutdown - Complete Ctrl+C interrupt handling and resource cleanup
- 🌐 Cross-Platform Support - Full support for Windows, Linux, macOS
- 📦 Rich Middleware Integration - Built-in MailKit, Redis, PostgreSQL, RabbitMQ support
- 🎯 Chinese Encoding Support - Native support for GBK/GB2312 and other Chinese encodings
🎯 Features
1. DDD Layered Architecture
The project adopts a standard DDD layered architecture with clear separation of concerns:
Smart.App/
├── Smart.App.Domain/ # Domain Layer - Core business logic
│ ├── Entities/ # Entities
│ └── Interfaces/ # Domain interfaces
├── Smart.App.Application/ # Application Layer - Application services
│ ├── BackgroundServices/ # Background services
│ └── Services/ # Application services
└── Smart.App.Infrastructure/ # Infrastructure Layer - Technical implementation
├── Configuration/ # Configuration management
└── Data/ # Data access
2. Modern Console Architecture
Built on Microsoft.Extensions.Hosting, providing:
- Background Service Support - Implement long-running background tasks via
BackgroundService - Graceful Shutdown - Complete Ctrl+C interrupt handling and resource cleanup
- Environment-Aware Configuration - Automatically load corresponding configuration files based on runtime environment
3. Automatic Service Registration
Integrated with Smart.Inject framework, supporting:
// Auto-register services via attributes
[Service(ServiceLifetime.Singleton, InjectScheme.OnlySelf)]
public class DataService
{
// Business logic implementation
}
// Scan and register all marked services
services.ScanRegisterServices(context.Configuration);
4. Enterprise Configuration Management
Supports multiple configuration sources for flexible application configuration:
builder.ConfigureAppConfiguration((context, config) =>
{
config.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true, true)
.AddEnvironmentVariables();
if (context.HostingEnvironment.IsDevelopment())
{
config.AddUserSecrets<Program>();
}
});
5. Rich Middleware Integration
Out-of-the-box enterprise middleware support:
- Smart.MailKit - Email sending service
- Smart.StackRedis - Redis cache service
- Smart.Npgsql - PostgreSQL database access
- Smart.RabbitMQ - Message queue service
- Smart.Channel - High-performance channel service
6. Intelligent Exception Handling
Automatically adjust exception handling strategy based on environment:
services.Configure<HostOptions>(options =>
{
// Development: Stop service on exception
// Production: Ignore exception, keep service running
options.BackgroundServiceExceptionBehavior =
context.HostingEnvironment.IsDevelopment()
? BackgroundServiceExceptionBehavior.StopHost
: BackgroundServiceExceptionBehavior.Ignore;
});
🚀 Quick Start
Install Template
dotnet new install Smart.App
Create New Project
# Create .NET 8 project
dotnet new smart.app -n MyDemo -f net8.0
# Create .NET 10 project
dotnet new smart.app -n MyDemo -f net10.0
Project Structure
After creation, the project will contain the following structure:
MyDemo/
├── MyDemo.Domain/ # Domain layer
│ ├── Entities/
│ │ └── People.cs
│ └── Interfaces/
│ ├── IRepository.cs
│ └── IPeopleRepository.cs
├── MyDemo.Application/ # Application layer
│ ├── BackgroundServices/
│ │ └── DemoHostedService.cs
│ └── Services/
│ ├── DemoService.cs
│ └── PeopleService.cs
├── MyDemo.Infrastructure/ # Infrastructure layer
│ ├── Configuration/
│ │ ├── ServiceConfigure.cs
│ │ └── ServiceExtensions.cs
│ └── Data/
│ ├── Repositories/
│ │ └── PeopleRepository.cs
│ └── DbContext.cs
└── MyDemo/ # Startup project
├── Program.cs
├── appsettings.json
├── appsettings.Development.json
├── appsettings.Staging.json
├── appsettings.Production.json
└── NLog.config
Implement Background Service
public class MyHostedService : BackgroundService
{
private readonly ILogger<MyHostedService> _logger;
private readonly IServiceScopeFactory _serviceScopeFactory;
public MyHostedService(ILogger<MyHostedService> logger, IServiceScopeFactory scopeFactory)
{
_logger = logger;
_serviceScopeFactory = scopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation($"{nameof(MyHostedService)} is running!");
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = _serviceScopeFactory.CreateScope();
var myService = scope.ServiceProvider.GetRequiredService<MyService>();
await myService.ExecuteAsync();
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
catch (OperationCanceledException)
{
_logger.LogInformation($"{nameof(MyHostedService)} is canceled.");
}
catch (Exception ex)
{
_logger.LogError(ex, $"{nameof(MyHostedService)} encountered an error.");
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}
}
}
Register Application Service
[Service(ServiceLifetime.Singleton, InjectScheme.OnlySelf)]
public class MyService
{
private readonly ILogger<MyService> _logger;
public MyService(ILogger<MyService> logger)
{
_logger = logger;
}
public async Task ExecuteAsync()
{
_logger.LogInformation("Executing service logic...");
// Business logic implementation
}
}
Configure Middleware
Configure required middleware in ServiceConfigure.cs:
public void Configure(IServiceCollection services, IConfiguration configuration)
{
// Configure email service
services.AddMailKit(configuration);
// Configure Redis cache
services.AddStackRedis(configuration);
// Configure PostgreSQL database
services.AddNpgsql(configuration);
// Configure RabbitMQ message queue
services.AddRabbitMQ(configuration);
// Other configurations...
}
📦 Deployment Guide
Deployment Mode Requirements
Important: This template must use the「Framework-Dependent」deployment mode
| Deployment Mode | Use Case | Template Support |
|---|---|---|
| Framework-Dependent (FDD) | Target machine has .NET runtime installed | ✅ Required |
| Self-Contained (SCD) | No runtime environment | ❌ Not supported |
Publish Command
# .NET 8 publish
dotnet publish -c Release --self-contained false -f net8.0
# .NET 10 publish
dotnet publish -c Release --self-contained false -f net10.0
Runtime Installation
Install the corresponding .NET runtime on the deployment target machine:
Recommend using .NET Runtime Installation Scripts for automated deployment.
🛠️ Development Guidelines
Service Registration Convention
This template uses the Smart.Inject framework for dependency injection. Please refer to its documentation for detailed usage:
DDD Best Practices
- Domain Layer - Keep it pure, no infrastructure dependencies
- Application Layer - Orchestrate domain logic, handle use cases
- Infrastructure Layer - Implement technical details like data access
Logging
Use NLog for logging, configuration file located at NLog.config:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd">
<targets>
<target name="logfile" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" />
<target name="console" xsi:type="ColoredConsole" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile,console" />
</rules>
</nlog>
Configuration Management
appsettings.json- Base configurationappsettings.Development.json- Development environment configurationappsettings.Staging.json- Staging environment configurationappsettings.Production.json- Production environment configuration
Chinese Encoding Support
The template has built-in Chinese encoding support, allowing direct use of GBK/GB2312 encoding for file read/write:
// Already configured in Program.cs
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
📋 Tech Stack
| Technology | Version | Description |
|---|---|---|
| .NET | 8.0 / 10.0 | Runtime framework |
| Microsoft.Extensions.Hosting | Latest | Generic host |
| Smart.Inject | Latest | Dependency injection framework |
| NLog | Latest | Logging framework |
| Smart.MailKit | Latest | Email service |
| Smart.StackRedis | Latest | Redis client |
| Smart.Npgsql | Latest | PostgreSQL client |
| Smart.RabbitMQ | Latest | Message queue client |
🤝 Contributing
Issues and Pull Requests are welcome to help improve this project!
📄 License
MIT License
👨💻 Author
Developed by zenglei
Developed by zenglei
This package has no dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.