I'm trying to do a c# console app (.net6.0).
Here is my program.cs
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
var cns = context.Configuration.GetConnectionString("db");
services.AddDbContext<DatabaseContext>(options => options.UseMySql(cns,ServerVersion.AutoDetect(cns) ));
})
.Build();
//Want to create new instance of Ghonta, without passing DatabaseContext parameter.
Ghonta g = new Ghonta();
Ghonta.cs-
public class Ghonta{
private readonly DatabaseContext db;
//Want to inject DatabaseContext from services
public Ghonta(DatabaseContext DB){
db = DB;;
}
}
I can't figure it out. Any help?
CodePudding user response:
You can register Gontha to your services, and get one from the Host instance after you have built it
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
var cns = context.Configuration.GetConnectionString("db");
services.AddDbContext<DatabaseContext>(options => options.UseMySql(cns,ServerVersion.AutoDetect(cns) ));
services.AddScoped<Ghonta>();
})
.Build();
Ghonta g = host.Services.GetRequiredService<Ghonta>();
You should be able to use Gontha as expected