1

I have some legacy code that accesses our database. I'd like to create an interface for each one of these classes for IoC/DI in unit testing.

All of the methods in these classes are static.

When I try to "extract an interface" via VisualStudio, it fails and says, "Could not extract an interface: The type does not contain any member that can be extracted to an interface".

There are some links that explain why interfaces shouldn't have static methods here and here.

This restriction appears to be mostly in support of polymorphism ... which I don't really care about right now and these classes don't really inherit from anything (other than Object).

So how do I use IoC to get an object I can pull data from?

I'd rather not make instance methods since instances increase the working set.

Community
  • 1
  • 1
micahhoover
  • 2,101
  • 8
  • 33
  • 53
  • 3
    You can't "inject" static classes - they are bound at compile time. If you want to use injection you'll have to inject instances. I suggest getting over your fear of "increasing the working set" and deal with that _if and when it becomes a problem_. – D Stanley Jan 12 '16 at 17:35
  • 1
    *"polymorphism [...] I don't really care about right now."* Yes, you do, because you'd *"like to create an interface for each one of these classes for IoC/DI in unit testing."* – Mark Seemann Jan 12 '16 at 17:55

2 Answers2

3

One technique could be to abstract the static classes away with a wrapper.

public MyStaticWrapper : IMyStaticWrapper
{
   public void SomeMethod(string something)
   {
      MyStatic.SomeMethod(something); 
   }
}

Then you can inject the IStaticWrapper where needed.


Sorry - just seen this bit....

I'd rather not make instance methods since instances increase the working set.

Tho I'm not sure if it would meet this requirement, but the footprint of the change is relatively small IMO. Personally I would agree with @DStanleys comment.

NikolaiDante
  • 18,469
  • 14
  • 77
  • 117
  • Apparently static classes are overrated since they don't reduce the footprint very much. http://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp – micahhoover Jan 12 '16 at 18:48
1

Depending on the goal, you could use something like Microsoft Fakes, in particular shims to intercept the static calls to bring the legacy code under a test harness.

Once your library is covered with tests you can have these as a safety net while you introduce proper DI, removing the statics if desired and fully isolated tests.

The danger is that shims are evil and can let developers get away with bad practice.

NikolaiDante
  • 18,469
  • 14
  • 77
  • 117