获取请求Ninject服务的类名

时间:2016-05-18 15:26:08

标签: c# ninject nlog

我抽象了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继续为context.Request.ParentRequest 返回 NULL。我也用context.Request.Target ........ 尝试了它仍然为context.Request.Target 返回NULL。我究竟做错了什么。请帮帮我!!!!

1 个答案:

答案 0 :(得分:0)

找到可能适合您的答案here,试一试:

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));
    }
}