...

/

Using the Data Cache in An API Controller Action Method

Using the Data Cache in An API Controller Action Method

Learn to use the data cache in an API controller action method.

Steps to use question cache in GetQuestion method

Now, we are going to make use of the questions cache in the GetQuestion method of our API controller. Work through the following steps:

  1. First, we need to make the cache available for dependency injection so that we can inject it into QuestionsController. So, let's register QuestionCache for dependency injection in the Program class after enabling the ASP.NET memory cache:

Press + to interact
...
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IDataRepository,DataRepository>();
builder.Services.AddMemoryCache();
builder.Services.AddSingleton<IQuestionCache,
QuestionCache>();
}

We register our cache as a singleton in the dependency injection system. This means that a single instance of our class will be created for the lifetime of the app. So, separate HTTP requests will access the same class instance and, therefore, the same cached data. This is exactly what we want for a cache. ...