In .NET Core console use dependency injection

This article describes how to use dependency injection features provided by Microsoft in the console application, use the master console, and can be extended to build windows service.

  • Create a Console Application
  • Add DependencyInjectionreferences
Install-Package Microsoft.Extensions.DependencyInjection
  • Create ServiceCollectionobjects, add service registration
var serviceCollection = new ServiceCollection()
    .AddSingleton<ICalculationService, CalculationService>();
  • Building ServiceProviderobjects
var serviceProvider = serviceCollection.BuildServiceProvider();
  • Access to services
var calcService = serviceProvider.GetService<ICalculationService>();

More introduce dependency injection, you can refer to the "ASP.NET Core Basic Use dependency injection"

Reference documents:

Guess you like

Origin www.cnblogs.com/youring2/p/11525038.html