Tuesday, August 2, 2016

Extracting an Interface from an existing class using Visual Studio 2015

If you ever work with a Brownfield application, you may find that you need to introduce proper design patterns for dependency injection and usage of IoC containers as well as support for Unit Testing into the application.

Of course, most dependency injection containers rely on casting an Interface to a concrete instance of a class and most Unit Testing frameworks such as Moq also rely on using Interfaces.

So what do you do if you do not have interfaces for your classes?

Well, thanks to the refactoring capabilities in Visual Studio 2015, you can extract the interfaces from  your concrete classes!

Simply do the following:

  1. Right click on the name of your class and select the menu option for "Quick Actions and Refactorings"
  2. You will then see a lightbulb icon appear to the left of your screen from which you can select the menu item: "Extract Interface"
  3. This will then present you with a dialog for selecting the methods and properties to include in your Interface.
  4. That is all there is to it!

Once you have the interfaces in place, you can use them as part of your IoC container as well as part of your Unit Tests!

How cool is that??

No comments:

Post a Comment