代码示例
public interface IMalemaLogger<T>
{
}
public class MalemaLogger<T> : IMalemaLogger<T>
{
private ILogger logger { get; set; }
public MalemaLogger(ILoggerFactory loggerFactory)
{
// 在这边可以得到T的类型
var name = "malema." + typeof(T).Name;
this.logger = loggerFactory.CreateLogger(name);
}
}
//注入的时候得用这个方式。
services.AddScoped(typeof(IMalemaLogger<>), typeof(MalemaLogger<>));
//使用它的地方
public class Worker
{
private readonly IMessageWriter _messageWriter;
private readonly Func<MalemaDbContext> _func;
private readonly IMalemaLogger<Worker> _malemaLogger;
public Worker(IMessageWriter messageWriter,
Func<MalemaDbContext> func,
IMalemaLogger<Worker> malemaLogger) //注入了
{
_messageWriter = messageWriter;
_func = func;
_malemaLogger = malemaLogger;
}
}