且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在.Net核心控制台应用程序中使用依赖注入

更新时间:2022-03-29 22:48:43

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

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>();