我在 .Net 7.0 中,在 Program.cs 中,我们没有任何具有依赖注入范围的函数。代码直接如下:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyModel;
using WebMarkupMin.AspNetCore7;
using WordPressPCL;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
// Add services to the container.
builder.Services.AddRazorPages();
var emailConfig = builder.Configuration
.GetSection("EmailConfiguration")
.Get<EmailConfiguration>();
builder.Services.AddSingleton(emailConfig);
//builder.Services.AddSitemap();
builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
我想在这里访问 IMemoryCache 并想在那里存储一些数据。我该怎么做?
一种方法是将
MemoryCache
注册为单例。它有一个优点,所有应用程序缓存都在一个地方。
var memoryCache = new MemoryCache(new MemoryCacheOptions());
builder.Services.AddSingleton<IMemoryCache>(memoryCache);
你可以用类似的东西来做到这一点
var app = builder.Build();
var cache = app.Services.GetRequiredService<IMemoryCache>();
cache.Set("key", "value", new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10000)
});
using Microsoft.Extensions.Caching.Memory;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Add memory cache
builder.Services.AddMemoryCache();
var app = builder.Build();
// Get memory cache instance
var cache = app.Services.GetRequiredService<IMemoryCache>();
//Set a value in cache
cache.Set("key", "value", new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10000)
});
app.UseHttpsRedirection();
app.UseSwagger();
app.UseSwaggerUI();
app.UseRouting();
app.MapControllers();
app.UseHttpsRedirection();
app.Run();
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
namespace MemoryCache;
[Controller]
[Route("api/[controller]")]
public class ExampleController : Controller
{
private readonly IMemoryCache _cache;
public ExampleController(IMemoryCache cache)
{
_cache = cache;
}
// GET
[HttpGet("{key}")]
public IActionResult Index(string key)
{
return Json(_cache.Get(key));
}
[HttpPost]
public IActionResult Create(string key, string value)
{
_cache.Set(key, value, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10000)
});
return Ok();
}
}
如果你愿意的话可以尝试一下 回购