我可以将ILogger注入控制器,但我在尝试将其注入存储库类时遇到问题. 这是我的启动方法: public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJ
这是我的启动方法:
public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddEnvironmentVariables(); Configuration = builder.Build(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Error() .WriteTo.RollingFile(Path.Combine( env.WebRootPath, "log-{Date}.txt")) .CreateLogger();}
这是在我的Configure方法中:
loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); loggerFactory.AddSerilog();
我的控制器:
private readonly ISkillsRepo _repo; private readonly ILogger _logger; public HistoryAndReportsController(Context db, ILogger<SkillsRepo> logger) { _repo = new SkillsRepo(db, logger); _logger = logger; }
回购:
private readonly Context _db; private readonly ILogger _logger; public SkillsRepo(Context db, ILogger<SkillsRepo> logger) { _db = db; _logger = logger; }
我可以将记录器注入控制器,然后将其传递给repo,但必须有一种方法将记录器直接注入repo但我找不到任何示例.
我可以在回购中创建另一个记录器实例,但这会破坏DI的目的.我有同样的问题,了解如何使用DBContext执行相同的操作.
public void ConfigureServices(IServiceCollection services) { ... services.AddScoped<IUserRepository, AwesomeUserRepository>(); ... }
ILoggerFactory(因此ILogger< T>)是framework provided injections并且不需要手动添加.