瞬态服务具有仅适用于第一个请求的函数
在我的ASP.NET Core 6 MVC项目中,我有一个瞬态服务contentservice
。此服务是从icontentservice
继承的,并添加到program.cs
使用
builder.Services.AddTransient<IContentService, ContentService>();
此处的实现:
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);
}
}
问题是每次请求contentservice
。 ,构造函数运行,readTexts()
被调用,这是一个重型功能,只能为第一个请求运行。 无论如何是否有使用仅用于第一个请求的代码块实现瞬态服务?请注意,我不能使用addsingleton
。
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
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望它持有数据,则必须将文字清单作为静态列表,仅应首先请求阅读。
尝试一下。
You have to make textList as static if you want it to hold data which should be read only on first request.
try this.