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

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

问题描述

我必须使用控制台应用程序将数据添加到我的数据库中.在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核心控制台应用程序中使用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核心控制台应用程序中使用依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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