【问题标题】:Net Core 3 - Accessing DBContext outside of the web apiNet Core 3 - 在 Web api 之外访问 DBContext
【发布时间】:2020-06-08 22:07:56
【问题描述】:

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

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

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();
    }

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

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

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

【问题讨论】:

    标签: c# asp.net-core-webapi asp.net-core-3.0


    【解决方案1】:

    实现您自己的 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

    【讨论】:

    • 谢谢!我已经设法将类重新创建为 BackgroundService 并通过 IServiceScopeFactory 使用了二元注入 - 工作正常!
    猜你喜欢
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2020-02-11
    • 2018-05-08
    • 1970-01-01
    相关资源
    最近更新 更多