Home > Software engineering >  Inject DbContext without explicitly passing as constructor argument in .net6.0 console app
Inject DbContext without explicitly passing as constructor argument in .net6.0 console app

Time:11-14

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

  • Related