本文主要介绍在.net Core 控制台程序中如何进行依赖注入,简单步骤如下
1、.NET Core Console项目安装引用Nuget包
Install-Package Microsoft.Extensions.Configuration.EnvironmentVariables Install-Package Microsoft.Extensions.Configuration.Json Install-Package Microsoft.Extensions.DependencyInjection Install-Package Microsoft.Extensions.Logging.Console Install-Package Microsoft.Extensions.Logging.Debug Install-Package Microsoft.Extensions.Options
2、使用Nuget的界面的管理器安装:
Microsoft.Extensions.Configuration.EnvironmentVariables Microsoft.Extensions.Configuration.Json Microsoft.Extensions.DependencyInjection Microsoft.Extensions.Logging.Console Microsoft.Extensions.Logging.Debug Microsoft.Extensions.Options
3、修改Program.cs文件
static void Main(string[] args) { var env = Environment.GetEnvironmentVariable("APP_ENVIRONMENT"); //根据环境变量读取配置文件 string appsetting = !string.IsNullOrEmpty(env) ? $"appsettings.{env}.json" : "appsettings.json"; var services = new ServiceCollection(); // 创建 config var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(appsetting, optional: false) .AddEnvironmentVariables() .Build(); services.Configure<ConnectionStrings>(configuration.GetSection("ConnectionStrings")); //注入
services.AddLogging(); services.AddTransient<ILoggerFactory, LoggerFactory>(); //注入数据库 var defaultConnection = connectionStrings.DBConnection; services.AddLinqToDbContext<DBContext>((provider, options) => { options.UseSqlServer(defaultConnection).UseDefaultLogging(provider); }); //调用 var serviceProvider = services.BuildServiceProvider(); var bar = serviceProvider.GetService<*********>(); bar.*******(); Console.WriteLine("Hello World!"); }