如何在自定义服务中注入Logger

时间:2019-05-31 04:53:53

标签: c# asp.net-core

我有ImportExportService。

在ConfigureServices方法的StartUp类中,我将其用作

services.AddImportExportService(Configuration.GetConnectionString("DefaultConnection"));

附加方法AddImportExportService:

public static class IServiceCollectionExtension
    {
        public static IServiceCollection AddImportExportService(this IServiceCollection services, 
            string connString,
            ILogger<ImportExportService> logger
            )
        {
            services.AddTransient<IImportExportService, ImportExportService>(provider => new ImportExportService(connString));
            return services;
        }
    }

ExportImportService使用日志记录。 我试图在ILoger<ImportExportService> logger之类的构造函数中将Logging in service作为参数注入,但是构造函数仅包含一个参数,并且扩展方法AddImportExportService得到错误。

如何在ExportImportService中注入日志记录?谢谢

1 个答案:

答案 0 :(得分:1)

services.AddTransient<IImportExportService, ImportExportService>(provider => new ImportExportService(connString));

应该是

services
    .AddTransient<IImportExportService, ImportExportService>(
        provider => new ImportExportService(connString, provider.GetRequiredService<ILogger<ImportExportService>>()));

假设ImportExportService的构造函数有两个参数。那么扩展名只需要两个参数:

public static IServiceCollection AddImportExportService(
    this IServiceCollection services, 
    string connString)