2

so I am putting together a project using NLog with Postsharp. I have a OnMethodBoundaryAspect attribute descendant to decorate classes and provide for intercepted execution for logging. My DI container is Unity.

So, using DI alone (not ServiceLocator), how would I resolve the Log object inside the aspect class to provide logging? In the past I have used ServiceLocator to resolve the log object, but I am trying to get away from that as I am really starting to believe that ServiceLocator really is an anti-pattern (yes I am aware that there is a bit of a holy war on this issue).

Thanks!

lstutzman
  • 23
  • 1
  • 2
  • 3
  • Update - I'm considering creating a custom TraceListener to wrap NLog, and then adding it to System.Diagnostic.Trace.Listeners. Then in the aspect, I could just write to that. – lstutzman Mar 08 '12 at 02:48
  • DI and a container give a solid way of doing AOP. If you model the system correctly, you can easily configure decorators that contain the logging. Or even if you don't, with Unity you can do interception to enable logging. Why do you think you still need PostSharp? – Steven Mar 08 '12 at 06:02
  • I've used unity interception before and could not deal with the performance overhead. I'm using postsharp because I don't want to deal with having to write all the decorator plumbing code. In retrospect I will probably just use the Ambient Context pattern to make logging available to the entire appdomain. – lstutzman Mar 08 '12 at 13:54
  • A good application design (that adheres to the [SOLID](http://en.wikipedia.org/wiki/SOLID) principles) will hardly ever need this. For instance, you can design your system around [command/handlers](http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91), which allows you do write a single decorator for logging that can be applied to all operations in the system. The performance is as good as with code weaving, and perhaps even better, because your application will consist of much less MSIL. – Steven Mar 08 '12 at 14:03

1 Answers1

2

add a static property logger in your class Aspect

public class LogAspect : OnMethodBoundaryAspect
{
    /// <summary>
    /// Gets or sets the logger.
    /// </summary>
    public static ILogger logger { get; set; }

set logger variable in your application init method with your ILogger class and exclude all methods before this initialization with AttributeExclude.

    [LogAspect(AttributeExclude = true)]
    protected void Application_Start()
    {
        _windsorContainer = new WindsorContainer();
        ApplicationDependencyInstaller.RegisterLoggingFacility(_windsorContainer);
        LogAspect.logger = _windsorContainer.Resolve<ILogger>();
nick2paris
  • 21
  • 3