如何在C#中获取Singleton实例
我是用mongodb创建一个Web API .NET 6 = aspnetcore-6.0& tabs = visual-studio“ rel =“ nofollow noreferrer”> tutorial 。
根据教程,您在program.cs文件中启动实例:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.Configure<BookStoreDatabaseSettings>(
builder.Configuration.GetSection("BookStoreDatabase"));
builder.Services.AddSingleton<BooksService>();
然后在控制器中获得实例:
public class BooksController : ControllerBase
{
private readonly BooksService _booksService;
public BooksController(BooksService booksService) =>
_booksService = booksService;
}
如何在控制器之外获取实例?
我也想添加为Singleton的第二堂课,此类中没有参数。我可以使用“ services.addsingleton”添加它,还是需要在“ services.configure”中做某事?我将如何获得实例?
I`m creating a Web Api .Net 6 with mongodb and I have been following this tutorial.
According to the tutorial, you start the instance in the Program.cs file like this :
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.Configure<BookStoreDatabaseSettings>(
builder.Configuration.GetSection("BookStoreDatabase"));
builder.Services.AddSingleton<BooksService>();
And you get the instance in the controller like this :
public class BooksController : ControllerBase
{
private readonly BooksService _booksService;
public BooksController(BooksService booksService) =>
_booksService = booksService;
}
How do I get the instance outside the controller ?
I also have a second class I wish to add as singleton, this class doesn't have arguments in it's constructor. Can I just add it using "Services.AddSingleton" or do I need to do something in "Services.Configure"? How would I get it's instance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论