I have a static class which calls a static Logger class,
e.g
static class DoesStuffStatic
{
public static void DoStuff()
{
try
{
//something
}
catch(Exception e)
{
//do stuff;
Logger.Log(e);
}
}
}
static class Logger
{
public static void Log(Exception e)
{
//do stuff here
}
}
How do I inject the Logger into my static class?
Note: I've read Dependency Injection in .NET with examples?, but this seems to use an instance logger.
Best Answer
This is not necessarily so. As long as your static logger exposes a method for:
Here's an example. Take the following class for DI:
And here's our static class which needs a logger:
Now, in a global startup for your app (in this case, in my global.asax.cs), you can instantiate your DI Container, then hand that off to your static class.
And presto! You are now up and running with DI in your static classes.
Hope that helps someone. I am re-working an application which uses a LOT of static classes, and we've been using this successfully for a while now.