We all know that Dependency Injection is a good thing. It is aligned with SOLID principles and gives us far more control over object lifecycles.
But, what to do when dealing with static methods?
Consider this for an example.
public interface ILogger
{
void Log(string message);
}
public interface IRepository
{
void DoSomething();
}
public class Logger : ILogger
{
......
}
public class Repository : IRepository
{
private ILogger logger;
public Repository (ILogger logger)
{
this.logger = logger;
}
public void DoSomething()
{
TestClass c = new TestClass();
c.ToGuid();
......
}
}
public static class MyExtensions
{
public static string ToGuid(this TestClass class)
{
// How do i get my logger here for logging??
}
}
It is a frequent situation where you are writing extension methods or utility methods. In most cases you SHOULD not need any dependencies but for argument's sake assume we need it.
Well, we can make use of Action or Func to ensure that abstraction is maintained. So I can potentially change the code like:
public static class MyExtensions
{
public static string ToGuid(this TestClass class, Action logAction)
{
if(logAction != null) { logAction("my message"); }
}
}
public class Repository : IRepository
{
private ILogger logger;
public Repository (ILogger logger)
{
this.logger = logger;
}
public void DoSomething()
{
TestClass c = new TestClass();
c.ToGuid(new Action(logger.Log);
......
}
}
But, what to do when dealing with static methods?
Consider this for an example.
public interface ILogger
{
void Log(string message);
}
public interface IRepository
{
void DoSomething();
}
public class Logger : ILogger
{
......
}
public class Repository : IRepository
{
private ILogger logger;
public Repository (ILogger logger)
{
this.logger = logger;
}
public void DoSomething()
{
TestClass c = new TestClass();
c.ToGuid();
......
}
}
public static class MyExtensions
{
public static string ToGuid(this TestClass class)
{
// How do i get my logger here for logging??
}
}
It is a frequent situation where you are writing extension methods or utility methods. In most cases you SHOULD not need any dependencies but for argument's sake assume we need it.
Well, we can make use of Action
public static class MyExtensions
{
public static string ToGuid(this TestClass class, Action
{
if(logAction != null) { logAction("my message"); }
}
}
public class Repository : IRepository
{
private ILogger logger;
public Repository (ILogger logger)
{
this.logger = logger;
}
public void DoSomething()
{
TestClass c = new TestClass();
c.ToGuid(new Action
......
}
}