ASP.NET Core中的静态Dictionary
字段,(静态或非静态?)ConcurrentDictionary
字段与依赖项注入单例服务之间有什么区别?
静态字典。
public class HomeController : Controller
{
private static IDictionary<string, string> _dictionary =
new Dictionary<string, string>();
}
A(静态还是非静态?)ConcurrentDictionary
。
public class HomeController : Controller
{
private IDictionary<string, string> _dictionary =
new ConcurrentDictionary<string, string>();
}
依赖项注入的单例服务中的Dictionary
属性。
// Startup.cs
services.AddSingleton<HomeService>(); // Dependency injection
// HomeService.cs
public class HomeService
{
public IDictionary<string, string> MyDictionary { get; set; } =
new Dictionary<string, string>();
}
// HomeController.cs
public class HomeController : Controller
{
private HomeService _service;
public HomeController(HomeService service)
{
_service = service;
}
public IActionResult Index()
{
_service.MyDictionary.Add("foo", "bar");
return Ok();
}
}
有什么区别?它们彼此之间有何不同?有什么方法比其他方法更受青睐吗?
答案 0 :(得分:0)
正如jpgrassi在评论中所指出的那样,在Controller内拥有一个静态字段并不是一个好主意,因为它无法跨负载平衡器后面运行的应用程序的多个实例进行扩展。
正确的方法是在ASP.NET Core中将distributed caching与IDistributedCache
接口一起使用,该接口允许使用不同的实现,例如内存中或Redis等。
public class HomeController : Controller
{
private readonly IDistributedCache _cache;
public HomeController(IDistributedCache cache)
{
_cache = cache;
}
public Task<IActionResult> Index()
{
var currentTimeUTC = DateTime.UtcNow.ToString();
byte[] encodedCurrentTimeUTC = Encoding.UTF8.GetBytes(currentTimeUTC);
var options = new DistributedCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(20));
await _cache.SetAsync("cachedTimeUTC", encodedCurrentTimeUTC, options);
return Ok();
}
}