tags:

views:

115

answers:

3

Scenario

I have a non-static class that wraps around Log4Net. This is really handy as it links up to a further application I have that displays logs of different processes that occur in a variety of software that I write (to allow me to see where errors occur, batch processes fail etc.)

Problem

This is all well and good, but if I want to log an entire process, I have to do a series of things:

  1. Instantiate the Logging object.
  2. Tell it to begin.
  3. Log stuff.
  4. Tell it to stop.

This means that if a process runs outside of the class I have to mess about passing the Logging object around which is a pain and looks messy.

Question

How can I essentially just declare the object in such a way that It is globally accessible by all the classes......and making it static isn't really an option, I don't think.

.....This could be a waste of time but I like opinions.

+5  A: 

It sounds like you want a singleton.

You can make a static property that returns the single instance of your class.

SLaks
+5  A: 

Why do you believe that making "it" static isn't an option? I suspect you're confusing the ideas of a static class and a static variable which maintains a reference to an instance of a non-static class.

public class Foo
{
    // Instantiate here, or somewhere else
    private static LogWrapper logWrapper = new LogWrapper(...); 
    public static LogWrapper LogWrapper { get { return logWrapper; } }
}

Just because the class is non-static doesn't mean you can't have a singleton instance of it which is globally available. Normally not such a good idea, but not too bad for logging.

If you do go down the singleton route, you may want to consider reading my article on implementing a singleton in C#.

Jon Skeet
I think he meant making the entire class static.
SLaks
@Slaks: And my point is that he doesn't have to. It's important to differentiate between a static class and a non-static class with an instance which is globally available. (That doesn't mean it *has* to be a singleton, but it might.)
Jon Skeet
I realize that; that's my point too. However, it sounds from your first line like you may have misunderstood him.
SLaks
@Slaks: Okay, will edit that first line.
Jon Skeet
+3  A: 

Rather than going down the static path or the Singleton path, you could investigate using Dependency Injection (DI) with an IoC Container framework. This would keep your classes testable and would decouple them from the logging class.

The IoC Container will handle lifetime management for you; by specifying container lifetime, you can simulate a Singleton with none of the disadvantages.

There is a learning curve, but it's worth it; DI has many other advantages.

EDIT: The trick is to avoid the Service Locator trap. Mark Seemann has some nice articles on this (and a book coming out).

TrueWill