如何在C#中获取Singleton实例

发布于 2025-01-24 06:58:14 字数 814 浏览 1 评论 0原文

我是用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文