I am using IMemoryCache in Asp.Net Core 2.1 Webapi project to temporarily store some data received from RabbitMq channel. I have a channel listener in a customised middleware. But when I try to access the data in the cache from controller, there is no data in it. I am using Autofac as my DI framework.
If I set a value to memory cache in a controller, I can get it from other classes, such as a service (also registered in Autofac DI) associated with this controller.
My implementation is as follow:
services.AddMemoryCache();
and then use the middleware as
app.UseMiddleware<RabbitMqConsumerMiddleware>();
app.UseCors("default")
.UseAuthentication()
.UseMvc();`
My Autofac registration is as follow:
Here is my Autofac registration
public IServiceProvider ConfigureServices(IServiceCollection services)
{
RabbitMqConfiguration rabbitMqConfiguration = new RabbitMqConfiguration();
Configuration.GetSection("RabbitMq").Bind(rabbitMqConfiguration);
services.AddSingleton(rabbitMqConfiguration);
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization()
.AddControllersAsServices()
.AddApiExplorer();
services.AddRabbitMq(rabbitMqConfiguration);
services.AddMemoryCache();
ContainerBuilder builder = new ContainerBuilder();
builder.Populate(services);
IContainer container = builder.Build();
return new AutofacServiceProvider(container);
}
In the middleware, I have
public RabbitMqConsumerMiddleware(RequestDelegate next, IMemoryCache memoryCache, RabbitMqConfiguration configuration, IModel messageBodyReceiverChannel) { _next = next; _memoryCache = memoryCache; _configuration = configuration; _messageBodyReceiverChannel = messageBodyReceiverChannel; } public async Task Invoke(HttpContext context) { bool isMessageBodyReceiverConsumerExist = _memoryCache.TryGetValue("message-body-receiver-consumer", out EventingBasicConsumer messageBodyReceiverConsumer); if (!isMessageBodyReceiverConsumerExist) { var messageBodyReceiverConsumer = new EventingBasicConsumer(_messageBodyReceiverChannel); messageBodyReceiverConsumer.Received += (ch, ea) => { MessageBody messageBody = JsonConvert.DeserializeObject<MessageBody>(Encoding.Default.GetString(ea.Body)); if (_memoryCache.TryGetValue("Message Body", out List<MessageBody> cacheMessageBodies)) { cacheMessageBodies.Add(messageBody); } else { _memoryCache.Set("Message Body", new List<MessageBody> { messageBody }); } }; _memoryCache.Set("message-body-receiver-consumer", messageBodyReceiverConsumer); } _messageBodyReceiverChannel.BasicConsume(_configuration.MessageReceiverQueue, false, messageBodyReceiverConsumer); await _next(context); }
where messageBody
comes from RabbitMq
In controller I have
[Authorize] [Route("[controller]")] [ApiController] public class MessageBodyController : ControllerBase { private readonly IApplicationService<Dto.MessageBody> _messageBodyPresenter; private readonly IMemoryCache _memoryCache; public MessageBodyController(IApplicationService<Dto.MessageBody> messageBodyPresenter, IMemoryCache memoryCache) { _messageBodyPresenter = messageBodyPresenter; _memoryCache = memoryCache; } [HttpGet] [Route("Stop")] public IActionResult Stop() { ((MessageBodyPresenter)_messageBodyPresenter).Stop(); return Ok(); } }
But _memoryCache
is always empty.
I put a breakpoint in my middleware and confirm that data has been set to the cache.
Do I use memory cache in a wrong way? Thanks
Without knowing your full configuration, I guess one issue could be that you have registered the new middleware after the Mvc middleware.
Your registration should look like this:
app.UseMiddleware<RabbitMqConsumerMiddleware>();
app.UseMvc();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.