ASP.NET Core 2+中的ILogger和DependencyInjection

时间:2018-09-01 03:31:57

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

我注意到function Replace-AllStringsInFile($SearchString,$ReplaceString,$FullPathToFile) { $content = [System.IO.File]::ReadAllText("$FullPathToFile").Replace("$SearchString","$ReplaceString") [System.IO.File]::WriteAllText("$FullPathToFile", $content) } 的{​​{1}}中没有明确的ILogger注册。

第一个问题:ConfigureServices如何注入到例如控制器。

第二个问题:如何配置Startup.cs注入中间件?

1 个答案:

答案 0 :(得分:8)

HostBuilder.Build过程中添加了日志记录

private void CreateServiceProvider()
{
    var services = new ServiceCollection();
    services.AddSingleton(_hostingEnvironment);
    services.AddSingleton(_hostBuilderContext);
    services.AddSingleton(_appConfiguration);
    services.AddSingleton<IApplicationLifetime, ApplicationLifetime>();
    services.AddSingleton<IHostLifetime, ConsoleLifetime>();
    services.AddSingleton<IHost, Host>();
    services.AddOptions();
    services.AddLogging();//<--HERE

    //...

WebHostBuilder.BuildCommonServices

    private IServiceCollection BuildCommonServices(out AggregateException hostingStartupErrors)
    {

        //... code removed for brevity

        var services = new ServiceCollection();
        services.AddSingleton(_options);
        services.AddSingleton<IHostingEnvironment>(_hostingEnvironment);
        services.AddSingleton<Extensions.Hosting.IHostingEnvironment>(_hostingEnvironment);
        services.AddSingleton(_context);

        var builder = new ConfigurationBuilder()
            .SetBasePath(_hostingEnvironment.ContentRootPath)
            .AddConfiguration(_config);

        _configureAppConfigurationBuilder?.Invoke(_context, builder);

        var configuration = builder.Build();
        services.AddSingleton<IConfiguration>(configuration);
        _context.Configuration = configuration;

        var listener = new DiagnosticListener("Microsoft.AspNetCore");
        services.AddSingleton<DiagnosticListener>(listener);
        services.AddSingleton<DiagnosticSource>(listener);

        services.AddTransient<IApplicationBuilderFactory, ApplicationBuilderFactory>();
        services.AddTransient<IHttpContextFactory, HttpContextFactory>();
        services.AddScoped<IMiddlewareFactory, MiddlewareFactory>();
        services.AddOptions();
        services.AddLogging();

要将ILogger注入到控制器中,只需将其作为依赖项包含在构造函数中

private readonly ILogger logger;

public MyController(ILogger<MyController> logger) {
    this.logger = logger;
}

//...

,并且框架在被激活时将注入到控制器中。

引用Dependency injection into controllers in ASP.NET Core

对于中间件vai构造函数注入,可以像使用控制器一样进行

或直接进入per-request dependenciesInvoke方法

public Task Invoke(HttpContext context, ILogger<MyMiddleware> logger) {
    //...
}

像其他注入服务一样

引用ASP.NET Core Middleware