Home > Mobile >  Transient service with a function that runs only for the first request
Transient service with a function that runs only for the first request

Time:07-11

In my asp.net core 6 mvc project, I have a transient service ContentService. This service is inherited from IContentService and added to Program.cs using

builder.Services.AddTransient<IContentService, ContentService>();

Here is the implementation of the service:

public interface IContentService
{
    public string GetText(int id);
}

public class ContentService : IContentService
{
    private readonly ContentDbContext _context;
    private List<string> textList;

    public ContentService(ContentDbContext context)
    {
        _context = context;

        ReadTexts();
    }

    public void ReadTexts()
    {
        // Reads text from the database and fills the textList.
        // THIS CODE MUST RUN ONLY FOR THE FIRST REQUEST.
    }

    public string GetText(int id)
    {
        return textList(id);
    }
}

The problem is every time ContentService is requested, the constructor runs and ReadTexts() is called, which is a heavy function that must only run for the first request. Is there anyway to implement a transient service with a code block that runs only for the first request? Note that I cannot use AddSingleton.

CodePudding user response:

You have to make textList as static if you want it to hold data which should be read only on first request.

try this.

public class ContentService : IContentService
{
    private readonly ContentDbContext _context;
    private static List<string> textList = new List<string>();

    public ContentService(ContentDbContext context)
    {
        _context = context;

        ReadTexts();
    }

    public void ReadTexts()
    {
       if(!textList.Any())
       {
        // Reads text from the database and fills the textList.
        // THIS CODE MUST RUN ONLY FOR THE FIRST REQUEST.
       }
    }

    public string GetText(int id)
    {
        return textList(id);
    }
}
  • Related