0

I am implementing Log4net in our application and for logging I am implementing AppenderSkeleton.

Since log4net resolves its appender using configuration setting I am not able to specify my custom service as a dependency injected using either constructor or property.

The reason I want to do so is because I want my appender to be unit tested using MOQ framework.

Following is a code sample of what I want to achieve.

public class LoggingAppender : AppenderSkeleton
{
    private ICustomService service;
    public LoggingAppender(ICustomService service)
    {
        this.service = service;
    }
    protected override void Append(log4net.Core.LoggingEvent loggingEvent)
    {
        service.Method("Data From loggingEvent");
    }
}

I also found the following answer on stackoverflow. But it doesn't serve the purpose for me.

Is there any solution to this issue or should we follow any other approach in order to unit test it?

Ashutosh Singh
  • 609
  • 6
  • 21
  • See the similar question: https://stackoverflow.com/questions/23634472/using-ioc-in-a-custom-log4net-appender – Igor Gnedysh Jan 15 '18 at 16:59
  • I guess since constructor injection is not available property injection would be a potential solution as suggested by the link provided by @IgorGnedysh. – Nkosi Jan 15 '18 at 17:03
  • Let me check how it fits with Windsor Castle DI container. – Ashutosh Singh Jan 15 '18 at 17:07
  • @Nkosi cant be done using Windsor Castle https://stackoverflow.com/questions/851940/windsor-castle-injecting-properties-of-constructed-object – Ashutosh Singh Jan 15 '18 at 17:29
  • @AshutoshSingh then all you have left is to redesign the class to use an abstract factory method that uses service locator anti-pattern or pure DI https://stackoverflow.com/a/30807022/5233410 – Nkosi Jan 15 '18 at 17:31
  • @IgorGnedysh any suggestion? – Ashutosh Singh Jan 15 '18 at 17:33
  • @Nkosi another link suggest that yes it can be done but the above link is latest compared to this one https://stackoverflow.com/questions/447193/resolving-classes-without-registering-them-using-castle-windsor – Ashutosh Singh Jan 15 '18 at 17:34

1 Answers1

0

@AshutoshSingh in that case I would suggest to add appender in runtime. see How to add log4net appender in runtime? (note that there's a bunch of levels where you could register appender, not only that one).

Also you may add factory regisration for ILogger which will add appender upon resolving, as an option (see Castle Windsor: How do I register a factory method, when the underlying type isn't accessible to my assembly?).

In any case by following that references you will have some info you could play with.

PS: do not have enough of reputation to reply in original thread :-) so will post answer here :-)

Igor Gnedysh
  • 144
  • 1
  • 10