c# 高级编程 20章451页 【依赖注入】【用配置文件配置服务】

309 阅读1分钟

使用配置文件配置服务

需要用配置文件中的配置信息来初始化服务的时候,可以将下面两个东西结合使用来达到目的:

  • .NET的配置IConfiguration
  • 对选项相关功能的扩展IServiceCollection.Configure<GreetingServiceOptions>(),这个方法的参数是IConfiguration类型

示例代码如下:

    class Program
    {
        static void Main()
        {
            DefineConfiguration();
            var container = RegisterServices();
            var controller = container.GetService<HomeController>();
            string result = controller.Hello("Katharina");
            Console.WriteLine(result);
        }

        static void DefineConfiguration()
        {
            IConfigurationBuilder configBuilder = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                 .AddJsonFile("appsettings.json");
            Configuration = configBuilder.Build();
        }

        public static IConfiguration Configuration { get; set; }

        static ServiceProvider RegisterServices()
        {
            var services = new ServiceCollection();
            services.AddOptions();
            services.AddSingleton<IGreetingService, GreetingService>();
            services.AddGreetingService(Configuration.GetSection("GreetingService"));
            services.AddTransient<HomeController>();
            return services.BuildServiceProvider();
        }
    }

appsettings.json文件:

{
  "GreetingService": {
    "From": "Matthias"
  }
}
    public class HomeController
    {
        private readonly IGreetingService _greetingService;
        public HomeController(IGreetingService greetingService)
        {
            _greetingService = greetingService;
        }
        public string Hello(string name) =>
            _greetingService.Greet(name);
    }

    public class GreetingService : IGreetingService
    {
        public GreetingService(IOptions<GreetingServiceOptions> options)
        {
            _from = options.Value.From;
        }

        private string _from;

        public string Greet(string name) => $"Hello, {name}! Greetings from {_from}";
    }
    
    public interface IGreetingService
    {
        string Greet(string name);
    }

    public static class GreetingServiceExtensions
    {
        public static IServiceCollection AddGreetingService(this IServiceCollection collection, IConfiguration config)
        {
            if (collection == null) throw new ArgumentNullException(nameof(collection));
            if (config == null) throw new ArgumentNullException(nameof(config));

            collection.Configure<GreetingServiceOptions>(config);
            return collection.AddTransient<IGreetingService, GreetingService>();
        }
    }
    public class GreetingServiceOptions
    {
        public string From { get; set; }
    }

输出是:

Hello, Katharina! Greetings from Matthias