Entity Framework Core Migrations with Azure Service Fabric

Entity Framework Core migrations are really powerful and most C# developers make good use of them. They’re very easy to use, you can work with them either on Powershell or on the Package Manager Console. Most of the time whenever you make some change in your Entities you can open up a terminal and hit “dotnet ef migrations add” followed by a name for your new migration.

This will work on all ASP.NET Core projects by default. However, when creating a Service Fabric Stateless or Stateful microservice, things are different. If you attempt to run this command it won’t work. You will receive an error like the following:

Unable to create an object of type ‘AppDbContext’. Add an implementation of ‘IDesignTimeDbContextFactory‘ to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

The first step to debugging this error is to re-run the command in verbose mode:

dotnet ef migrations add "InitialMigration" --verbose

By taking a closer look to the console output we can see that the actual error that broke the operation is the following exception:

System.MissingMethodException: No parameterless constructor defined for this object.

Every time you run that command without supplying any other arguments, .NET Core will re-build your project, execute Program.cs to load the webhost and more specifically the Startup file. This is important because without the startup file, it will be impossible for the runtime to know how to instantiate the Database Context.

This is an example of an AppDbContext:

We only have one entity, the ToDo model and we inherit from Entity Framework’s DbContext. If you look at the constructor, you can see that in order to create a new instance of this class we have to pass an argument of type DbContextOptions. The most common option in that object is the connection string that will allow Entity Framework to locate our database. The options object is created by a DbContextOptionsBuilder in the startup class at the time of registration like this:

So what is really happening is that the runtime can’t provide DbContextOptions so it resorts to calling the parameter-less constructor. But there’s no such thing. We haven’t implemented one. And it’s neither the best choice nor possible sometimes. So, the framework suggests we implement the IDesignTimeDbContextFactory interface. It’s not necessary, we can quickly solve this issue by adding the following lines to our Program.cs file:

This function will build a webhost and load the Startup file. That way, when .NET Core builds the project it will know how to create an instance of the DBContext because it will be registered with the ASP.NET Core Dependency Injection Container

Note that attempting to call this method from inside Main will cause your Service Fabric build to fail because it will hijack the default port 5000. Doing so will cause any subsequent microservice build to fail.

Using the HttpClient the correct way

The other day I was building a small demo ASP.NET Core 2.0 application for the purposes of a video course I’m preparing on the upcoming second version of .NET Core.

The application was making several http requests to third party APIs. I noticed that it was taking unusually long to finish. At first I thought that something was wrong with the preview version of .NET Core and curious to find out why I ported it to the stable .NET Core 1.1 and started filling the code with stopwatches to discover the source of the lag.

What I found out was that I have been using the HttpClient all wrong. And probably so do you. All the countless C# books, tutorials and courses out there all mention that the correct usage of the HttpClient is withing a ”using’ statement.

The flow of this thought goes something like this: The HttpClient holds unmanaged resources, it also implement the IDisposable interface. When it comes to other IDisposables like the StreamReader we wrap them in ‘using’ statements so we should do the same with HttpClient.

The problem is, that’s not the case! Creating a new instance of the HttpClient every time we make a request and disposing it after the request completes is not the most sensible thing to do as it turns out. You’re better off having a single HttpClient instance. You can achieve this by creating a wrapper for the HttpClient and either declare it as static or register it as a singleton with your preferred IoC container. The second solution seems more elegant and avoids the static cling code smell.

But let’s take it from the beginning. After the discovering what made my application so slow, I figured I could run a test. So I created a .NET Core Console Applciation from scratch. I then went on to creating two classes, the SlowWay and the FastWay static classes. (I know, awful names). Both classes make several requests to this url: http://jsonplaceholder.typicode.com/photos.

The SlowWay classes follows the famous ‘using’ convention. The FastWay class uses the same HttpClient for all requests

And here’s how I tested them:

With the RequestCount set to 30 I got the following results:


The slow approach takes almost double the time, something that proves my fears about the ‘using’ statement

Increasing the RequestCount to 30 results in almost triple performance decrease:


Increasing to 60 got me even closer to 3 times increase in performance improvement when using the fast approach.

Imagine the performance increase that little modification can lead to in Microservices Oriented Applications.

After digging around the internet for quite some time I stumbled upon an awesome article that describes the source of the issue. Apparently, it’s a TCP socket issue. Check the article from ASP.NET Monsters for more information.

Oh and stop wrapping your HttpClients in ‘using’ statements when making multiple requests. I certainly will.

The whole project is available in this repo: https://github.com/dimlucas/HttpClientPerformanceTest

Overloading the indexer operator in C#

There’s a feature in C# that’s very useful for some use cases, yet many people seem to overlook it. I’m talking about the indexer operator. What this operator does is, it makes it possible to access elements of an enumerable data structure that your class makes use of, with the familiar [] operator.

Let’s say we have a class named Car:

Now let’s say that we have multiple cars, multiple instances of the class Car and that we want to organize them in a collection. What should we use? A plain old Generic List you might say and you would be correct, but what happens if we want to augment that list with more operations, more car-specific operations. Perhaps we want to clean the cars, or repair them. All that logic can nicely go inside a class named Garage:

As you can see we still use a List to store the cars, but we’re using the delegate pattern. A generic list has a bunch of methods but we only need three of them, the Add(), ElementAt() and Remove() methods. Oh and we also need the Count property so that we know how many cars we have.

This is an initial draft of our garage class showing the use of the delegate pattern. We can also include other stuff to make the class resemble real-life garage even more

The addition of the Clean() and Repair() methods improves our Garage implementation but there’s something missing. Every time we want to access a specific car by index we are forced to use the Get() method. It’s counter-intuitive. Here’s where the powerful indexer operator comes into play. After we’ve implemented an indexer operator in our collection class we will be able to access car elements with array-like syntax, like this:

Let’s see how simple it is to do that

So basically, you override the indexer operator like a property, with a getter and a setter. In this particular example we don’t want to be able to manipulate the contents of the garage so we don’t need a setter. But using a setter is a totally legitimate operation and one you will probably find pretty helpful once you start using it. That’s how easy it is 🙂

Check the whole project on this GitHub repo

Loose Coupling in C# Explained

Hello everyone, in this tutorial I want to provide you with a simple as possible, yet comprehensive enough example of what loose coupling really is and why it’s useful. Understand loose coupling and you’re going to have another advanced software engineering concept under your belt.

Before we start, I’m going to borrow the Loose Coupling definition from Wikipedia:
In computing and systems design a loosely coupled system is one in which each of its components has, or makes use of, little or no knowledge of the definitions of other separate components. Sub-areas include the coupling of classes, interfaces, data, and services.

The key takeaway from this is the phrase “little to no knowledge”. Object oriented programming and design offers multiple layers of abstraction for your application. That’s another key-word, “Abstraction”. Everyone who has ever taken a course on OOP or read an OOP book has stumbled upon this word and probably knows how OOP helps you achieve Polymorphism. The benefits of loose coupling include:

• Cleaner Code: After applying loose coupling your code is going to be much easier to read
• More Maintainable Code: Your code will also be easier to change
• Testable Code: This is the reason why beginners see no need for loose coupling. Because most beginners do not unit test and don’t know how hard it is to unit test tightly coupled code
• Scalable Code: I understand that in a small application loose coupling might not make any noticeable difference but in large scale projects it just makes your life a lot easier

The easiest way to explain loose coupling is actually to explain the exact opposite, tight coupling. Tight coupling is when one or more classes in your application is highly dependent on one or more other classes. Take this class hierarchy for example:

class ClassA
    public ClassA() { }

class ClassB
    public ClassB()
        _foo = new ClassA();

    private ClassA _foo;

In this simple example, ClassB contains an instance of ClassA and ClassB is responsible for creating that instance. So in this implementation ClassB needs to have knowledge about the inner workings of ClassA. Remember that we want ClassB to have little or no knowledge about how ClassA operates or how its objects get instantiated. The above code using loose coupling will look like this:

class ClassA : IMyInterface
    public ClassA() {  }

class ClassB
    public ClassB(IMyInterface foo)
        _foo = foo;

    private IMyInterface _foo;

An interface, in this very simplistic example called MyInterface, is introduced to solve the conflict. That way, any class that implements IMyInterface can be passed to class B who no longer needs to know how to instantiate it.

To provide a more real-world example, I will create a Console Application project with some rather simple functionality. It’s going to display some to-dos in the console and whether those To-Dos have been completed or not. (The full code of this project can be found here).

I’m going to create a “Models” folder to place my ToDo class first:

I tried to keep it as simple as possible, after all this is just a console application.

Next let’s create the class with the basic to-do functionality. For the sake of demonstration I’m going to actually create two classes. One will be tight coupled, the other will be loosely coupled. Let’s name them TightlyCoupledToDos and LooselyCoupledToDos respectively.

For now the two classes are essentially identical:

public class TightlyCoupledToDos
    public class TightlyCoupledToDos

    public async Task<IEnumerable<ToDo>> All()

public class LooselyCoupledToDos
    public LooselyCoupledToDos()


    public IEnumerable<ToDo> All()


Both have an All() method that returns a list of to-dos. The interesting part in how these two classes are going to populate the to-do list. In a real world application data like that probably come from a service. So let’s go ahead and create our ToDoService in a ‘Services’ folder:

public class ToDoService
    public IEnumerable<ToDo> GetAll()

This is an initial form of the service. Because we don’t have an API or a database we are going to fetch data from JSONPlaceholder’s ToDo list which can be found here https://jsonplaceholder.typicode.com/todos

To parse the JSON data we will use Newtonsoft’s NuGet package. To add it:
• Right click on your project
• Go to ‘Manage NuGet Packages’
• Go to the ‘Browse’ tab
• Search for ‘Newtonsoft.Json’
• Click Install

Next we will use an HttpClient and the Newtonsoft.JsonConvert class to get the data from the API and parse them to a list of ToDo objects:

A simple enough, service implementation. It uses an instance of the HttpClient class to asynchronously read JSON data the feed them to the Json Converter for deserialization.

After having created the service, let’s use it in our TightlyCoupledToDos class to get some data.

You see the service in initialized in the constructor and the All() method uses the service to get the parsed data and return it

Let’s go in our Program.cs file to make use of the TightlyCoupledToDos class and display the list of to-dos on screen

class Program
    static void Main(string[] args)

    static async void ToDos()
        TightlyCoupledToDOs vm = new TightlyCoupledToDos();
        IEnumerable<ToDo> todos = await vm.all();
        foreach(ToDo todo in todos)

The Console.ReadLine() statement is there to keep the console window open for us, so that we can see the results. The ToDos() method instantiates the TightlyCoupledToDos class, gets the todos asynchronously and writes them to the output:


So far so good, our classes all work and the absence of loose coupling has yet to come back and bite us. But what if we need to use another service. There are several reasons why we would want to replace the ToDoService with something else:
• We might want to test our code with fake data provided by fake service
• We might want to support different sources of data like files, APIs or databases
• We might want to conditionally supply a service to the ToDos class according to some event

It’s hard to do so when the ToDos class heavily depends on a specific service implementation. As you might have guessed it’s time to get ourselves some loose coupling. Here’s what we need to do:

• Create a IToDoService interface that will be implemented by any supporting service
• Modify our ToDoService to implement the IToDoService interface
• Create a TestToDoService that also implements IToDoService
• Modify LooselyCoupledToDos to work with either service

The implementation of the IToDoService is pretty simple:

And in ToDoService:

Now let’s create another service that will return local data to the caller instead of calling an API or querying a database. This is a rather common practice during unit tests.

The TestToDoService implements the IToDoService differently. Instead of using an HttpClient to get JSON data from the web, this class creates a list and fills it up with some dummy data to be sent to the caller for testing

Now this is the most important step of them all! We need to go to our LooselyCoupledToDos class and make it support what its name says it supports. In order to do that, the class needs to hold a reference to an IToDoService object and not a ToDoService or TestToDoService object. It also needs to take that reference as a constructor argument rather than instantiating on its own. That way our LooselyCoupledToDo class knows nothing about the actual service and thus we will have achieved the precious separation of concerns we want.

Now that we’ve implemented our classes in a loosely coupled way let’s see how easy it is to switch services. Let’s introduce a static field in our Program class that will be true if the app is in test mode and therefore needs to use test data or false if the application is not in test mode and must fetch real data:

If _testMode is true the LooselyCoupledToDos is initialized with the test service, if it is not it gets initialized with the real service.

You can see the whole project in my GitHub repository dedicated to C# here

Now that you’ve learned what loose coupling is, it’s time to take it one step further and learn about Inversion Of Control and Dependency Injection. I will be writing on those soon. Until then, keep coding!!