静态字段和控制器中注入的单例之间的区别?

Difference between a static field and a injected singleton in controller?

静态 Dictionary 字段、(静态或非静态?)ConcurrentDictionary 字段和 ASP.NET 控制器中的依赖注入单例服务之间有什么区别核心?

静态字典。

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

A 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();
    }
}

有什么区别?它们彼此有何不同?有哪一种方法优于另一种方法吗?

正如评论中 jpgrassi 所指出的,在 Controller 中有一个静态字段不是一个好主意,因为它不能跨应用程序的多个实例进行扩展 运行负载均衡器。

正确的做法是 ASP.NET 核心是使用 distributed cachingIDistributedCache 接口,它允许不同的实现,例如内存或 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();
    }
}