Starting up with ASP.Net Core + Docker
Hello! Welcome to this small introduction of ASP.Net Core and Docker.
In the present article I will try to show you the main benefits of using ASP.Net Core with Docker Integration. I hope to get your attention and interest in this magnificent combination of technology.
You will learn:
- To create a basic web application using ASP.Net Core, dockerized.
- To personalize the generated code to create an app with Entity Framework Core, using the Database First approach.
- A suggested architecture for creating apps consuming a web API for code reutilization.
You will need to know:
- A basic understanding of relational databases, and Object Relational Mapping.
- Ability to create a MS SQL Database.
You will need to have
- Visual Studio 2017 or another similar IDE.
- Microsoft SQL Server 2017, configured and able to create databases.
- Docker installer.
- Probably some coffee or another caffeine-based beverage.
Ready? Let’s start!
What is .Net?
The .Net Framework is a software framework developed by Microsoft. It includes a large class library and provides language interoperability across several programming languages, like C# and Visual Basic.net. Programs written for .NET Framework execute in a software environment named the Common Language Runtime (CLR). The CLR is an application virtual machine that provides services such as security, memory management, and exception handling.
The Framework provides UI, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications.
.NET Eco System
Microsoft has been busy in the last years, expanding the .NET Ecosystem.
As you can be seen below, we will focus in .NET Core.
What is ASP.NET?
ASP.NET is the recommend way Microsoft gives us to create robust web applications. Create MVC Applications is very easy.
You can utilize the Razor languange to build views. In a nutshell, it allows to insert C# code inside HTML, increasing the productivity.
For more information about ASP.NET, you can review many articles. The official page: https://dotnet.microsoft.com/learn/dotnet/what-is-dotnet
What is ASP.NET Core?
ASP.Net Core is the next evolution of ASP.Net. It’s a reimplementation of ASP.Net as a modular web framework, and others components like Entity Framework. ASP.NET Core is cross-platform (not only runs on Windows, but also on Linux and macOS) and is open-source. Also includes: built-in dependency injection, has integration of client-side frameworks and it’s lightweight and high-performance.
What is MVC?
The Model View Controller is not new. It is originated in the 1970’s, with several implementations in different platforms. The pattern has evolved and even gave origin to derivatives, like MVP (Model View Presenter), used in Classic Windows Forms, and MVVM (Model View View Model), used in WPF applications.
Even of its origins for desktop applications, MVC has been widely adopted as an architecture for World Wide Web applications in major programming languages. One of those implementations is ASP.NET MVC and the new ASP.NET Core MVC.
This pattern allows to create easier to test, lightweight applications.
MVC separates and application in three main components or “layers”:
Model: Classes that have the entity data of the application. The logic, business rules and entity validation are contained here. Usually model objects are mapped to be retrieved and persisted in a relational database.
View: UI components or pages that allows the user to interact with the application. This UI will display and allow modification in the model data.
Controller: Classes that handle http(s) requests. The controllers handle the user input.
Advantages & disadvantages
Simultaneous development: Multiple developers can work simultaneously on the model, controller and views.
High cohesion: MVC enables logical grouping of related actions on a controller together. The views for a specific model are also grouped together.
Low coupling: There is low coupling among models, views or controllers.
Ease of modification: Because of the separation of responsibilities, future development or modification is easier.
Multiple views for a model — Models can have multiple views, depending on what the user needs to see, or edit.
Code navigability — The framework navigation can be complex because it introduces new layers of abstraction.
What is Docker?
Docker is a program that performs operating-system-level virtualization.
Virtualization is the act of creating a virtual version of something, including virtual computer hardware platforms, storage devices, and computer network resources.
Virtualization began in the 1960s, as a method of logically dividing the system resources provided by mainframe computers between different applications.
Docker is used to run software packages called containers. Containers are isolated from each other and bundle their own application, tools, libraries and configuration files; they can communicate with each other through well-defined channels. All containers are run by a single operating-system kernel and are thus more lightweight than virtual machines. Containers are created from images that specify their precise contents. Images are often created by combining and modifying standard images downloaded from public repositories.
Installation of Docker (windows)
The first step is to download Docker. I’m using a Windows OS, so I will get that version. If you’re using Mac, select the appropriate version.
You can get the installer in the following address: https://www.docker.com/get-started
I suggest you get the stable version.
Double-click Docker for Windows Installer to run the installer.
When the installation finishes, Docker starts automatically. The whale icon in the notification area indicates that Docker is running, and accessible from a terminal.
To verify that everything is running fine, keep reading. You can still make progress even if something is not ready in your Docker installation.
Creating a New MVC .NET Core Application with Docker Support
For the next tutorial, I will be creating a new ASP.Net Core MVC Application.
I will create a small demo of a Stock Trading tool wannabe, to keep track of financial investments.
Open Visual Studio 2017 and select File >> New >> Project…
A new window with appear, with all the available templates installed. Choose Visual C# >> .NET Core >> ASP.NET Core Web Application, as shown below. For this tutorial example, I’m naming my solution Graham, in reference to Benjamin Graham, a pioneer in Stock Analysis and Valuation methods for financial instruments (known as Securities).
I will be using GitHub for source control.
A new wizard window will appear. Here you have to select the Framework version (.NET Core), and the version of ASP.NET Core (2.1 in my example).
Select the right icon as shown in the screenshot Web Application (Model-View-Controller).
Choose ‘Enable Docker Support’.
For the Authentication, I will not select any. That would exceed the limits of this tutorial.
For real life applications this might be very important.
If you need to select any, you will have the following options, as shown below:
This allows to use windows accounts or even cloud-based authentication.
Press the OK button, and Visual Studio should generate a basic template with all the internal plumbing required to start developing the application.
If everything is successful, in the Solution Explorer of Visual Studio you will have something similar to the next screenshot:
Also, if you enabled the ‘Create new Git Repository’ before, your Team Explorer should be ready to create the new Repository, using your GitHub credentials. It’s very useful to keep Visual Studio up to date and linked with your GitHub account. That setup exceeds this tutorial, but you can get an excellent tutorial here: https://blogs.msdn.microsoft.com/benjaminperkins/2017/04/04/setting-up-and-using-github-in-visual-studio-2017/
Also here, the official page of the extension for Visual Studio.
Here, with the Publish button, you will get a new repository created, with the initial files of your solution, now you can code safe and keep up version control of your files. From now on, Visual Studio will keep track of your changes, files added and enable you to share and work with teammates.
Now the real fun begins, writing the application. But before, make sure everything was generated correctly. Since we want to test things separately, first we will test that the Web App runs ok, but without Docker. We are going to use IIS Express (Internet Information Services), provided by Visual Studio.
Given our preferences in the setup of the application, Visual Studio will have preselected the option ‘Docker’ on the launcher. We don’t want to test that just yet. Select ‘IIS Express’ first, then start the application. If not compiled before, it will be compiled now, as usual.
If everything is right, your favorite web browser will start, with your new generated application loaded.
Excellent, now let’s test Docker.
First, open a shell or Power Shell. Then type the commands:
docker run hello-world
This will start pulling from the internet some images, and then show you a demo from the Docker team. Now you have validated that your installation is working fine.
Now, get back to Visual Studio, switch back to Docker in the Launch Selector, and launch the application with Docker.
In my case, I had to make Docker switch to windows, because of my OS.
This can be done with Right Click on the Whale Icon of docker in your notification tray, and then selecting “Switch to Windows Containers…” If you see instead “Switch to Linux Containers”, you should be set.
If you have troubles launching the app on Docker, this article helped me. https://stackoverflow.com/questions/46779911/asp-net-core-docker-build-error
Running your app will take some time, because Docker has to download images to work. Finally, you should see the application running in your default browser:
Having tested the generated application dockerized, now we can finally start developing something new.
First, we are going to need a Database. I will be using Microsoft SQL Server 2017, but any similar database will and should work.
For this example, I’m showing a demo application to track Stocks (called also Portfolio), the Operations you made with them (buy, sell), and the offers made (an offer to sell or buy).
This application will have to be tiny, but it will show the basics:
Using Entity Framework Core with the ‘Database First’ style, for creating Models for MVC.
The entity relationship diagram of this tiny database is:
Installing Entity Framework Core
Entity Framework Core is not a part of .NET Core and standard .NET framework. It is available as a NuGet package. You need to install NuGet packages for the following two things to use EF Core in your application:
- EF Core DB provider
- EF Core tools
Let’s install the above NuGet packages in the .NET Core console application in Visual Studio 2017.
Install EF Core DB Provider
First, we need to install the NuGet package for the provider of the database we want to access. Since we want to access MS SQL Server database, we need to install
Microsoft.EntityFrameworkCore.SqlServer NuGet package.
To install the DB provider NuGet package, right click on the project in the Solution Explorer in Visual Studio and select Manage NuGet Packages…
This will open NuGet Package Manager UI. Click on the Browse or the Updates tab and search for Microsoft.entityframeworkcore in the search box at the top left corner, as shown below.
Choose the provider package for the database you want to access. In this case select
Microsoft.EntityFrameworkCore.SqlServer for MS SQL Server as shown above. (make sure that it has the .NET symbol and the Author is Microsoft). Click Install to start the installation.
Finally, accept the license terms associated with the packages that are going to be installed.
This will install the
Microsoft.EntityFrameworkCore.SqlServer package. Verify it in Dependencies > NuGet, as shown below.
Notice that the provider NuGet package also installed other dependent packages such as
Install Entity Framework Core Tools
Along with the DB provider package, you also need to install EF tools to execute EF Core commands. These make it easier to perform several EF Core-related tasks in your project at design time, such as migrations, scaffolding, etc.
EF Tools are available as NuGet packages. You can install NuGet package for EF tools depending on where you want to execute commands: either using Package Manager Console (PowerShell version of EF Core commands) or using dotnet Command Line interface.
Install EF Core Tools from Command Line
If you want to execute EF Core commands from .NET Core’s CLI (Command Line Interface), first install the NuGet package
Microsoft.EntityFrameworkCore.Tools.DotNet using NuGet UI.
Microsoft.EntityFrameworkCore.Tools.DotNet package, edit the .csproj file by right clicking on the project in the Solution Explorer and select Edit <projectname>.csproj. Add
<DotNetCliToolReference> node as shown below. This is an extra step you need to perform in order to execute EF Core 2.0 commands from dotnet CLI in VS2017.
Now, open the command prompt (or terminal) from the root folder of your project and execute EF Core commands from CLI starting with dotnet ef, as shown below.
Creating a Model for an Existing Database in Entity Framework Core
Here you will learn how to create the context and entity classes for an existing database in Entity Framework Core. Creating entity & context classes for an existing database is called Database-First approach.
We will be using reverse engineering using the
Scaffold-DbContextcommand. This reverse engineering command creates entity and context classes (by deriving
DbContext) based on the schema of the existing database.
Let’s create entity and context classes for the following Graham database in the local MS SQL Server shown below.
Tip: You will need a Connection String, as usual. You can get it easily from the Properties window selecting the database from the Server Explorer:
Scaffold-DbContext to create a model based on your existing database. The following parameters can be specified with Scaffold-DbContext in Package Manager Console:
Scaffold-DbContext [-Connection] [-Provider] [-OutputDir] [-Context] [-Schemas>] [-Tables>]
[-DataAnnotations] [-Force] [-Project] [-StartupProject] [<CommonParameters>]
In Visual Studio, select menu Tools -> NuGet Package Manger -> Package Manger Console and run the following command, changing the values to your system configuration, instance name, database name, etc.:
Scaffold-DbContext “Data Source=DESKTOP-91VKTF3;Initial Catalog=Graham;Integrated Security=True” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Scaffold-DbContext command creates entity classes for each table in the
SchoolDBdatabase and context class (by deriving
DbContext) with Fluent API configurations for all the entities in the Models folder.
The following is the generated
Security entity class for the
As you can see, there is a fast and clean iso morphism with the table that will persist the entity Security.
I suggest that you see the
GrahamContextclass which you can use to save or retrieve data.
You can get all the source code in here: https://github.com/Konigstiger/Graham
This is just scratching the surface of these technologies combined.
I hope I got your attention and made you wonder about the benefits of these technologies.
Next suggested steps would be:
Create a Web API, and make the MVC Web Application invoke it. This is a better solution in general, following the current trend of API-First. This approach will give you the possibility to create an API that can be consumed by different systems and devices.
You could use Xamarin to create a Mobile Application, for Android or iOS, that consumes your web API.
Your website (like our example) could also invoke the same web API, but give a different perspective, more tools, or more customization options. However, it should be mobile friendly too!
The architecture would be something like this:
Don’t forget that using Docker will give you the possibility of a clean and lean deploy, with reduced costs. Using a Web API will also enable a great code reutilization. And all that is good, real good.
That’s all I have now to show you now. I hope this guide will give you enthusiasm and motivation to get a good start with ASP.NET Core and Docker!
Thank you for your time, and happy coding!
References and further reading
Docker Official reference
(text in spanish, a very well illustrated guide)
Entity Framework and Entity Framework Core
ASP.NET Core and Docker