So I was wondering what's the best approach to attach another DbContext
to my ASP.NET app. I'm trying to achieve DbContext
that I can use anywhere in my code not only in controllers. I tried to add it as service but failed. In Configure
i'm creating a new class with IHubContext
to connect to clients, but i also need to retrieve data from database so i was thinking maybe about editing constructor Baloon
and adding DbContext
as required. I wanna hear from you guys what's gonna be the best.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<DiscordContext>();
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
StartBalloon(app.ApplicationServices.GetRequiredService<IHubContext<BalloonHub>>());
...
}
private static void StartBalloon(IHubContext<BalloonHub> context)
{
Globals.Bln = new Balloon(context); // Starting balloon
}
DiscordContext.cs
public class DiscordContext : DbContext
{
public DbSet<DbUser> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("---connection_string----");
}
}
Baloon.cs
public class Baloon
{
private IHubContext<BalloonHub> _context;
private DbContext _db;
private List<BalloonPlayer> _currentPlayerList = new();
public int? WhenToPop;
public int? CurrentLevel;
public int? BotValue;
public int? CurrentValue;
public bool Pooped;
public bool Running;
public Balloon(IHubContext<BalloonHub> context)
{
_context = context;
Task.Run(Main); // Let's imagine that there is need for data from database(DbContext)
}
}