平时做技术实践时,很多问题不是概念不会,而是细节没串起来。拿“.NET开发中全局数据存储的常见方式”来说,它看着像小点,放到项目里常会牵出环境、配置、兼容性和维护成本。下面按实际采用顺序,把思路、关键写法和容易踩坑的地方讲清楚,便于大家直接对照操作。
实现方法
public static class GlobalData
{
public static string ApplicationName { get; set; } = "MyApp";
public static int MaxConnections { get; } = 100;
private static readonly ConcurrentDictionary<string, object> _cache
= new ConcurrentDictionary<string, object>();
public static void SetCache(string key, object value)
{
_cache[key] = value;
}
public static T GetCache<T>(string key)
{
return _cache.TryGetValue(key, out var value) ? (T)value : default;
}
}
特点
优缺点
1. appsettings.json (ASP.NET Core)
{
"AppConfig": {
"Theme": "Dark",
"Timeout": 30
}
}
采用方式
// 在Startup中配置
services.Configure<AppConfig>(Configuration.GetSection("AppConfig"));
// 注入使用
public class MyService
{
private readonly AppConfig _config;
public MyService(IOptions<AppConfig> config)
{
_config = config.Value;
}
}
2. 用户设置 (WinForms/WPF)
// 保存设置
Properties.Settings.Default.Theme = "Dark";
Properties.Settings.Default.Save();
// 读取设置
var theme = Properties.Settings.Default.Theme;
特点
ASP.NET Core 示例
// 注册服务
services.AddSingleton<IGlobalCache, MemoryCache>();
services.AddScoped<IUserSession, UserSession>();
// 使用
public class MyController : Controller
{
private readonly IGlobalCache _cache;
public MyController(IGlobalCache cache)
{
_cache = cache;
}
}
特点
生命周期:
线程安全:取决于实现
适用场景:ASP.NET Core 应用、服务共享
实现方法
// 注册
services.AddMemoryCache();
// 使用
public class DataService
{
private readonly IMemoryCache _cache;
public DataService(IMemoryCache cache)
{
_cache = cache;
}
public string GetCachedData(string key)
{
return _cache.GetOrCreate(key, entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30);
return ExpensiveDatabaseCall();
});
}
}
特点
实现方法
// 使用Redis
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
});
// 使用
public async Task<byte[]> GetCachedDataAsync(string key)
{
return await _distributedCache.GetAsync(key);
}
特点
实现方法
// 中间件中设置
app.Use(async (context, next) =>
{
context.Items["RequestStartTime"] = DateTime.UtcNow;
await next();
});
// 控制器中访问
var startTime = HttpContext.Items["RequestStartTime"] as DateTime?;
特点
访问方式
var envVar = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
特点
实现方法
// 使用EF Core
public class AppDbContext : DbContext
{
public DbSet<GlobalSetting> GlobalSettings { get; set; }
}
// 使用
var setting = await _dbContext.GlobalSettings
.FirstOrDefaultAsync(s => s.Key == "MaintenanceMode");
特点
| 存储方式 | 生命周期 | 持久化 | 分布式兼容 | 典型采用场景 |
|---|---|---|---|---|
| 静态成员 | 应用程序域 | 否 | 否 | 全局常量、轻松缓存 |
| 应用程序设置 | 持久化 | 是 | 部分 | 应用设置、用户偏好 |
| 依赖注入容器 | 取决于注册类型 | 否 | 否 | 服务共享、全局服务 |
| 内存缓存 | 应用程序 | 否 | 否 | 频繁访问的临时数据 |
| 分布式缓存 | 持久化 | 是 | 是 | 多实例共享数据 |
| HttpContext.Items | 请求期间 | 否 | 否 | 请求级数据传递 |
| 环境变量 | 进程/系统 | 是 | 是 | 部署设置、环境特定设置 |
| 数据库存储 | 持久化 | 是 | 是 | 需持久化的全局设置 |
1.按需选择:根据数据特性(大小、访问频率、生命周期)选择合适方式
2.分层设计:
3.线程安全:
4.性能考虑:
5.测试友好:
6.分布式场景:
public class HybridCache
{
private readonly IMemoryCache _memoryCache;
private readonly IDistributedCache _distributedCache;
public HybridCache(IMemoryCache memoryCache, IDistributedCache distributedCache)
{
_memoryCache = memoryCache;
_distributedCache = distributedCache;
}
public async Task<T> GetOrCreateAsync<T>(string key, Func<Task<T>> factory, TimeSpan expiration)
{
if (_memoryCache.TryGetValue(key, out T memoryValue))
{
return memoryValue;
}
var distributedValue = await _distributedCache.GetStringAsync(key);
if (distributedValue != null)
{
var value = JsonSerializer.Deserialize<T>(distributedValue);
_memoryCache.Set(key, value, expiration);
return value;
}
var newValue = await factory();
_memoryCache.Set(key, newValue, expiration);
await _distributedCache.SetStringAsync(key,
JsonSerializer.Serialize(newValue),
new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = expiration });
return newValue;
}
}
// Program.cs
builder.Services.Configure<AppConfig>(builder.Configuration.GetSection("AppConfig"));
builder.Services.AddSingleton<IOptionsMonitor<AppConfig>>(provider =>
provider.GetRequiredService<IOptionsMonitor<AppConfig>>());
// 使用
public class ConfigService
{
private readonly AppConfig _config;
public ConfigService(IOptionsMonitor<AppConfig> configMonitor)
{
_config = configMonitor.CurrentValue;
configMonitor.OnChange(newConfig =>
{
_config = newConfig;
});
}
}
理解这一步时,借助合理选择和组合这些全局数据存储方式,能够构建出既高效又易于维护的 .NET 应用程序架构。
到此这篇关于.NET开发中全局数据存储的常用方式的文章就介绍到这了,更多相关.NET全局数据存储内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多兼容脚本之家!