【问题标题】:Inject DbContext without explicitly passing as constructor argument in .net6.0 console app注入 DbContext 而无需在 .net6.0 控制台应用程序中显式传递为构造函数参数
【发布时间】:2022-11-14 01:57:31
【问题描述】:

我正在尝试做一个 c# 控制台应用程序(.net6.0)。

这是我的程序.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;;
    }

}

我想不通。有什么帮助吗?

【问题讨论】:

  • 用你的依赖注入注册它

标签: c# console-application .net-6.0


【解决方案1】:

您可以将 Gontha 注册到您的服务中,并在构建后从 Host 实例中获取一个

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.AddService<Gontha>();
})
.Build();

var gontha = host.GetRequiredService<Gontha>();

您应该可以按预期使用 Gontha

【讨论】:

    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多