【发布时间】:2016-05-18 15:26:08
【问题描述】:
我正在抽象出 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 for context.Request.ParentRequest。我也用 context.Request.Target 尝试过......它仍然为 context.Request.Target 返回 NULL。我究竟做错了什么。请帮帮我!!!!
【问题讨论】:
-
@dbugger 所以我从你建议的链接中了解到,如果我通过 IResolutionRoot.Get
() 访问 Ninject 服务,ParentContext 或 Target 将为空,就像我在上面的控制台应用程序中所做的那样。知道了!!。非常感谢。 -
但是有没有办法让注入的类使用 IResolutionRoot 通知它自己到 Ninject 服务,这样 ParentContext 就不会为空
-
“我正在抽象出 NLog。”这不是抽象,而是复制确切的 API。请考虑使用this approach。
-
@Steven 谢谢。我喜欢你在给我的链接上的回答。