Reputation: 327
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
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:
Upvotes: 2