How to use Dependency Injection in .Net core Console Application

泪湿孤枕 提交于 2020-12-29 03:44:34

问题


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

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

This gives the following error:

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.

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


回答1:


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


来源:https://stackoverflow.com/questions/48369845/how-to-use-dependency-injection-in-net-core-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!