5

I believe the first of the code examples is a short-hand Singleton implementation and I'm not sure if it is thread safe. As the class, EventSourceLogger derives from EventSource, which is not static, this class can not just be a static class itself (which would have been even more convenient - tradeoffs between singletion and static notwithstanding).

I reverted from a more thorough specific known thread safe implementation to this implementation for brevity - after liking the look of this approach in a colleagues code. What have I lost?

Current implementation

[EventSource(Name = "EventSourceLogger")]
public class EventSourceLogger : EventSource
{
    public static readonly EventSourceLogger Logger = new EventSourceLogger();`
}

Previous implementation

[EventSource(Name = "EventSourceLogger")]
public class EventSourceLogger : EventSource
{
    private static EventSourceLogger instance;

    private EventSourceLogger()
    {
    }

    public static EventSourceLogger Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new EventSourceLogger();
             }

            return instance;
        }
    }
}
brumScouse
  • 3,166
  • 1
  • 24
  • 38
  • Lazy loading, but from what I can see, not a lot else. Well, aside from now exposing the logger as a Field instead of a Property, which has an impact on type structure and reflection. – Adam Houldsworth Feb 15 '16 at 11:32
  • That makes sense, this is still a singleton implementation though isn't it? I was initially confused by this approach and a similar approach just using static classes. – brumScouse Feb 15 '16 at 11:43
  • Yes it is. The end result is the same from a logical perspective, but there are behavioural differences (not many though). That said, I would favour migrating away from this approach to a DI approach with a lifetime manager that enforces the singleton semantics you require. – Adam Houldsworth Feb 15 '16 at 11:58
  • I can see where you're coming from with the DI approach, however, this would mean in the root of my application I would be both creating the root composition (setting up the container) registering the Logger against the container and then using service location to get at the logger for other setup (SLAB setup in Global.asax). The lifetime of the logger and container are essentially the same anyway. – brumScouse Feb 15 '16 at 12:04
  • Yeah there are some hoops to jump through, for small apps I wouldn't bother but for large apps it seems like work at first but then tends to be taken advantage of later. – Adam Houldsworth Feb 15 '16 at 12:06

0 Answers0