C# 依赖注入 配置依赖注入

我们知道 Asp.net程序里面已经有自动配置好这个依赖注入的设置了。很多时候我们也需要在我们的控制台程序这边使用依赖注入来共享代码。

使用Nuget添加一些Package包

  • 添加引用 Microsoft.Extensions.DependencyInjection 一个Console类型的程序,是不会带有这个依赖注入的包,我们需要手动添加这个引用。 通常我们的程序还会依赖于 IConfiguration,和ILogger<> 所以我们也需要把下面的这些包添加我们的项目当中
  • Microsoft.Extensions.Configuration.Json
  • Microsoft.Extensions.Configuration.Binder
  • Microsoft.Extensions.Configuration.EnvironmentVariables
  • Microsoft.Extensions.Logging

创建一个DIConfig来返回ServiceProvider

using Malema.net.Example;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;

namespace Malema
{
    public static class DIConfig
    {
        public static IServiceProvider ConfigureServices()
        {
            var serviceCollection = new ServiceCollection();
            var configuration = new ConfigurationBuilder()
           .SetBasePath(AppContext.BaseDirectory)
           .AddJsonFile("appsettings.json", true)
           .AddEnvironmentVariables()// 把环境变量也放到 Configuraiton当中
           .Build();

            serviceCollection.AddSingleton((IConfiguration)configuration);

            // 注入了ILogger<>
            serviceCollection.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(configuration.GetSection("Logging")); //配置logging的一些东西
                // 下面的这行需要 Microsoft.Extensions.Logging.Console
                loggingBuilder.AddConsole(); //加多个 每一个Ilooger下面就会有多个provider
            });

            // 注入了一个默认的ILogger
            serviceCollection.AddSingleton<Microsoft.Extensions.Logging.ILogger>((it) =>
            {
                return it.GetService<ILoggerFactory>().CreateLogger("categtory");
            });

            Register(serviceCollection);

            return serviceCollection.BuildServiceProvider();
        }

        private static void Register(IServiceCollection serviceCollection)
        {
            //在这边注入了我们需要的类了, 这两个类我们在上一节有介绍到了
            serviceCollection.AddSingleton<IMessageWriter, MessageWriter>();
            serviceCollection.AddSingleton<Worker>();
        }
    }
}

使用ServiceProvider

using Malema.net.Example;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;

namespace Malema.net
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var sp = DIConfig.ConfigureServices();
            var worker = sp.GetService<Worker>(); //把worker对象从容器中取出来
            await worker.ExecuteAsync();
        }
    }
}

第一次我们需要用GetService的方式取出我们的入口点的对象。 sp.GetRequiredService<> 这个方法如果找不到需要的对象是会抛出异常 sp.GetService<>() 找不到的话会返回null

最近更新的
...