如何在 .Net core 控制台应用程序中使用依赖注入 [英] How to use Dependency Injection in .Net core Console Application

查看:36
本文介绍了如何在 .Net core 控制台应用程序中使用依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用控制台应用程序将数据添加到我的数据库中.在 Main() 方法中,我添加了:

I have to add data to my database using a Console Application. In the Main() method I added:

var services = new ServiceCollection();
var serviceProvider = services.BuildServiceProvider();
var connection = @"Server = (localdb)mssqllocaldb; Database = CryptoCurrency; Trusted_Connection = True; ConnectRetryCount = 0";
services.AddDbContext<CurrencyDbContext>(options => options.UseSqlServer(connection));

在另一个类中,我添加了使用数据库的功能,使其像一个 Web Api 应用程序,并将我的 DbContext 添加到构造函数中:

In another class I add functionality to work with database, and made it like a Web Api application and added my DbContext into constructor:

public AutoGetCurrency(CurrencyDbContext db) =>  this.db = new CurrencyDbContext();

出现以下错误:

未将对象引用设置为对象的实例

Object reference not set to an instance of an object

我尝试添加一个没有参数的默认构造函数,它仍然给出同样的错误.

I tried to add a default constructor without parameters, and it still gives the same error.

请告诉我如何在 .Net core 控制台应用程序中使用 DI ?

Please tell me how I can use DI in .Net core console application ?

推荐答案

在构建提供程序之前将服务添加到集合.在您的示例中,您在已经构建了提供程序之后添加了服务.对集合所做的任何修改对构建后的提供程序都没有影响.

Add services to collection before building provider. In your example you are adding services after already having built the provider. Any modifications made to the collection have no effect on the provider once built.

var services = new ServiceCollection();
var connection = @"Server = (localdb)mssqllocaldb; Database = CryptoCurrency; Trusted_Connection = True; ConnectRetryCount = 0";
services.AddDbContext<CurrencyDbContext>(options => options.UseSqlServer(connection));
//...add any other services needed
services.AddTransient<AutoGetCurrency>();

//...

////then build provider 
var serviceProvider = services.BuildServiceProvider();

同样在构造函数示例中,前提是您仍在初始化数据库.

Also in the constructor example provided you are still initializing the db.

public AutoGetCurrency(CurrencyDbContext db) =>  this.db = new CurrencyDbContext();

注入的数据库未被使用.您需要将注入的值传递给本地字段.

The injected db is not being used. You need to pass the injected value to the local field.

public AutoGetCurrency(CurrencyDbContext db) =>  this.db = db;

一旦配置正确,您就可以通过提供程序解析您的类,并让提供程序在解析请求的服务时创建和注入任何必要的依赖项.

Once configured correctly you can then resolve your classes via the provider and have the provider create and inject any necessary dependencies when resolving the requested service.

var currency = serviceProvider.GetService<AutoGetCurrency>();

这篇关于如何在 .Net core 控制台应用程序中使用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆