Mik1893
Mik1893

Reputation: 327

Net Core 3 - Accessing DBContext outside of the web api

i'm building a small webapi to work in conjunction with additional functionalities running in the background.

In the specific case I have a class called 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();
    }

That I'm trying to run together with the web api. BotManagerContext is a DbContext initialized in the web api, i'm trying to retrieve it using dependency injection - so i'm trying to add the TelegramBot class into the Startup.cs file so that it starts as a Singleton and can retrieve the dbcontext

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

Question is - how do I implement this? using an interface? I'm fairly new to this and I don't know how to implement it :) Thanks

Upvotes: 0

Views: 299

Answers (1)

YankTHEcode
YankTHEcode

Reputation: 652

Implementing your own IHostedService would be the best way to go about this. For getting the dbcontext in the service you can use IserviceProvider as your dependency. Serviceprovider will give you the dbcontext. You can configure your custom hosted service to be added as a singleton then. Check this documentation for details:

https://learn.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

Upvotes: 2

Related Questions