其他分享
首页 > 其他分享> > .NET Core Console控制台项目中使用DI依赖注入(ConfigureServices)

.NET Core Console控制台项目中使用DI依赖注入(ConfigureServices)

作者:互联网

本文主要介绍.NET Core(C#) Console项目中,实现DI依赖注入的方法步骤,及实现和ASP.NET Core项目一样使用ConfigureServices()方法配置服务,以及相关实现的示例代码。

1、.NET Core Console项目安装引用Nuget包

1)使用Nuget管理控制台

集成到项目中的最简单方法是使用NuGet。您可以通过打开包管理器控制台(PM)并键入以下语句来安装依赖:

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图形管理器

使用Nuget的界面的管理器分别搜索:

"Microsoft.Extensions.Configuration.EnvironmentVariables"

"Microsoft.Extensions.Configuration.Json"

"Microsoft.Extensions.DependencyInjection"

"Microsoft.Extensions.Logging.Console"

"Microsoft.Extensions.Logging.Debug"

"Microsoft.Extensions.Options"

=> 然后找到点击"安装"

3)使用.NET CLI命令安装

> dotnet add TodoApi.csproj package Microsoft.Extensions.Configuration.EnvironmentVariables
> dotnet add TodoApi.csproj package Microsoft.Extensions.Configuration.Json
> dotnet add TodoApi.csproj package Microsoft.Extensions.DependencyInjection
> dotnet add TodoApi.csproj package Microsoft.Extensions.Logging.Console
> dotnet add TodoApi.csproj package Microsoft.Extensions.Logging.Debug
> dotnet add TodoApi.csproj package Microsoft.Extensions.Options

相关文档:VS(Visual Studio)中Nuget的使用

2、添加修改.NET Core Console项目

1) 修改Program.cs文件

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading.Tasks;
internal class Program
{
    public static async Task Main(string[] args)
    {
        // 创建ServiceCollection
        var services = new ServiceCollection();
        ConfigureServices(services);
        // 创建ServiceProvider
        var serviceProvider = services.BuildServiceProvider();
        // app程序运行入口
        await serviceProvider.GetService<App>().Run(args);
    }
    private static void ConfigureServices(IServiceCollection services)
    {
        // 配置日志
        services.AddLogging(builder =>
        {
            builder.AddConsole();
            builder.AddDebug();
        });
        // 创建 config
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false)
            .AddEnvironmentVariables()
            .Build();
        services.Configure<AppSettings>(configuration.GetSection("App"));
        // 添加 services:
        // services.AddTransient<IMyRespository, MyConcreteRepository>();
        // 添加 app
        services.AddTransient<App>();
    }
}

2)添加App类

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Threading.Tasks;
public class App
{
    private readonly ILogger<App> _logger;
    private readonly AppSettings _appSettings;
    public App(IOptions<AppSettings> appSettings, ILogger<App> logger)
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        _appSettings = appSettings?.Value ?? throw new ArgumentNullException(nameof(appSettings));
    }
    public async Task Run(string[] args)
    {
        _logger.LogInformation("Starting...");
        Console.WriteLine("Hello cjavapy!");
        Console.WriteLine(_appSettings.Name);
        _logger.LogInformation("Finished!");
        await Task.CompletedTask;
    }
}

鸣谢:https://www.cjavapy.com/article/735/
https://www.cjavapy.com/

标签:Core,Console,ConfigureServices,Extensions,Logging,services,using,Microsoft
来源: https://www.cnblogs.com/yakniu/p/16529730.html