我正在抽象NLog。到目前为止,我所拥有的。。。
public interface IAppLogger
{
void Info(string message);
void Warn(string message);
void Error(string message, Exception error);
void Fatal(string message);
....// other overload
}
用NLog-实现IAppLogger
public class NLogLogger : IAppLogger
{
private readonly NLog.Logger _logger;
public NLogLogger([CallerFilePath] string callerFilePath = "")
{
_logger = NLog.LogManager.GetLogger(callerFilePath);
}
public void Info(string message)
{
_logger.Info(message);
}
public void Warn(string message)
{
_logger.Warn(message);
}
.....// and others
}
以及使用此服务的控制台应用程序
public class Program
{
private static IAppLogger Log { get; set; }
private static void Main()
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
Log = kernel.Get<IAppLogger>();
Log.Info("Application Started");
Log.Warn("Developer: Invalid date format");
Log.Error("Divid by zero error", new DivideByZeroException());
Console.WriteLine("nDone Logging");
Console.ReadLine();
}
}
以及使用Ninject的依赖项注入
public class NinjectConfig : NinjectModule
{
public override void Load()
{
Bind<IAppLogger>().To<NLogLogger>()
.WithConstructorArgument("callerFilePath", GetParentTypeName);
}
private static string GetParentTypeName(IContext context)
{
return context.Request.ParentRequest.Service.FullName;
}
}
到目前为止还不错。但是,当我运行应用程序时,Ninject会不断为上下文返回NULL。Request.ParentRequest。我也在上下文中尝试过。Request.Target……..对于上下文,它仍然返回NULL。请求。目标。我做错了什么。请帮帮我!!!!
在这里找到了一个可能对你有用的答案,试试看:
public class NLogLogger : IAppLogger
{
private readonly NLog.Logger _logger;
public NLogLogger(Type callerType)
{
_logger = NLog.LogManager.GetLogger(callerType.Name,callerType);
}
public void Info(string message)
{
_logger.Info(message);
}
public void Warn(string message)
{
_logger.Warn(message);
}
.....// and others
}
public class NinjectConfig : NinjectModule
{
public override void Load()
{
Bind<IAppLogger>().ToMethod(p => new NLogLogger(p.Request.Target.Member.DeclaringType));
}
}