![](/img/trans.png)
[英]Can't pass in configuration section to IServiceCollection.Configure<T>() anymore
[英].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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.