Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inject DbContext without explicitly passing as constructor argument in .net6.0 console app

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-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading