How to use Dependency Injection in .Net core Console Application

后端 未结 1 534
自闭症患者
自闭症患者 2021-02-07 23:41

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

var services = new ServiceCollection();
var serviceProvider = servic         


        
1条回答
  •  日久生厌
    2021-02-08 00:11

    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(options => options.UseSqlServer(connection));
    //...add any other services needed
    services.AddTransient();
    
    //...
    
    ////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();
    

    0 讨论(0)
提交回复
热议问题