实用技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > ASP.NET > 实用技巧 > .NET全局数据存储

.NET开发中全局数据存储的常见方式

作者:百锦再@新空间

在 .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 应用、服务共享

四、内存缓存 (IMemoryCache)

实现方式

// 注册
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();
        });
    }
}

特点

五、分布式缓存 (IDistributedCache)

实现方式

// 使用Redis
services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

// 使用
public async Task<byte[]> GetCachedDataAsync(string key)
{
    return await _distributedCache.GetAsync(key);
}

特点

六、HttpContext.Items (ASP.NET Core)

实现方式

// 中间件中设置
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全局数据存储内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文