Castle Windsor won't inject Logger in a property!

前端 未结 3 554
再見小時候
再見小時候 2020-12-19 07:56

I try to inject log4net in a ILogger property of my service class but the property is always NULL!

I\'ve seen this topic but it doesn\'t help me!

How can I g

相关标签:
3条回答
  • 2020-12-19 08:28

    You could also initialize your Logger by using:

    public ILogger Logger { get; set; }
    
    public MyController()
    {
         Logger = NullLogger.Instance;
    }
    
    0 讨论(0)
  • 2020-12-19 08:34

    A problem is where you are checking it:

     public ILogger Logger
        {
            get { return logger; }
            set { logger = value; }
        }
    
        public LogicClass1()
        {
            logger.Debug("Here logger is NullLogger!");
        }
    

    The property injection will not happen until after the constructor is run, so checking the property value in the constructor will never show the value you are expecting

    0 讨论(0)
  • 2020-12-19 08:48

    I was having the same problem. It was always null.

    I managed to solve the problem by injecting the logger in the constructor this way:

    public ILogger logger;
    
    public MyController(ILogger logger)
    {
        this.logger = logger;
    
        logger.Info("Something");
    }
    
    0 讨论(0)
提交回复
热议问题