Net Core 3 - 在网络之外访问 DBContext api

Net Core 3 - Accessing DBContext outside of the web api

我正在构建一个小型网络api,以便在后台与其他功能结合使用运行。

在特定情况下,我有一个名为 TelegramBot 的 class:

public class TelegramBot
{
    static ITelegramBotClient botClient;
    private readonly BotManagerContext _botManagerContext;

    public TelegramBot(BotManagerContext botManagerContext)
    {
        _botManagerContext = botManagerContext;

        botClient = new TelegramBotClient("xxxx:yyyyy");
        botClient.OnMessage += Bot_OnMessage;
        botClient.StartReceiving();
    }

我正在尝试 运行 与网络 api。 BotManagerContext 是在网络 api 中初始化的 DbContext,我正在尝试使用依赖注入来检索它 - 所以我正在尝试将 TelegramBot class 添加到 Startup.cs 文件中,以便它作为单例启动,可以检索 dbcontext

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<BotManagerContext>(opt =>
              opt.UseSqlite("Data Source=BotManager.db"));
        services.AddControllers();
        services.AddSingleton<TelegramBot>();
    }

问题是 - 我该如何实施?使用界面?我对此很陌生,我不知道如何实现它:) 谢谢

实施您自己的 IHostedService 是解决此问题的最佳方式。要在服务中获取 dbcontext,您可以使用 IserviceProvider 作为您的依赖项。 Serviceprovider 会给你 dbcontext。 您可以将自定义托管服务配置为添加为单例。查看此文档了解详细信息:

https://docs.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/background-tasks-with-ihostedservice#implementing-ihostedservice-with-a-custom-hosted-service-class-deriving-from-the-backgroundservice-base-class