【问题标题】:.NET Core 5.0 - IServiceCollection.Configure and ILogger.NET Core 5.0 - IServiceCollection.Configure 和 ILogger
【发布时间】:2021-07-09 14:58:47
【问题描述】:

我有一个注册其服务的库:

public static IServiceCollection AddViewStringRenderer(this IServiceCollection services, string contentRootPath, ILogger logger)
{
    services.Configure<RazorViewEngineOptions>(options => { options.ViewLocationExpanders.Add(new ViewLocationExpander(contentRootPath, logger)); });
    services.AddTransient<IRazorViewToStringRenderer, RazorViewToStringRenderer>();
    ...
    return services;
}

如您所见,我需要一个用于services.Configure&lt;RazorViewEngineOptions&gt;(...) 的记录器,因此它是此扩展方法的一个参数。

但由于该方法用于Startup.ConfigureServices(),我们无法在.NET 5 中实例化ILogger。如何将记录器传递给services.Configure()

【问题讨论】:

    标签: c# asp.net-core dependency-injection .net-5


    【解决方案1】:

    好的,非常感谢 David Fowler 指出了这种模式 - Resolving services when using IOptions

    结果如下:

    public class RazorViewEngineConfigureOptions : IConfigureOptions<RazorViewEngineOptions>
    {
        private readonly ILogger<ViewLocationExpander> _logger;
        private readonly string _contentRootPath;
    
        public RazorViewEngineConfigureOptions(IHostEnvironment env, ILogger<ViewLocationExpander> logger)
        {
            _contentRootPath = env.ContentRootPath;
            _logger = logger;
        }
    
        public void Configure(RazorViewEngineOptions options)
        {
           options.ViewLocationExpanders.Add(new ViewLocationExpander(_contentRootPath, _logger));
        }
    }
    
    public static class RegisterServices
    {
        public static IServiceCollection AddEmailerService(this IServiceCollection services)
        {
            services.AddSingleton<IConfigureOptions<RazorViewEngineOptions>, RazorViewEngineConfigureOptions>();
            services.AddTransient<IRazorViewToStringRenderer, RazorViewToStringRenderer>();
    
            ...
            return services;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 2020-04-21
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      相关资源
      最近更新 更多