.NET Core 5.0 - IServiceCollection.Configure 和 ILogger

.NET Core 5.0 - IServiceCollection.Configure and ILogger

我有一个注册其服务的图书馆:

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<RazorViewEngineOptions>(...) 的记录器,因此它是此扩展方法的参数。

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

好的,非常感谢 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;
    }
}