.NET 5 – One to rule them all!

“There can be only one!” – This is my favourite quote from the 90s classic – Highlander movie. Today, another classic, perhaps not as old but still fairly mature is getting a total makeover. 18-year old – .NET 5 is here. And just like the immortal Scottish swordsman, it has succeeded in turning a lot otherwise separate frameworks into a single powerful framework.

.NET Core, Xamarin and the old .NET Framework have now become a single .NET 5 Framework. The unified platform will allow you to target Windows, Linux, macOS, iOS, Android, tvOS, watchOS, WebAssembly and more. The new version has undergone some heavy optimizations and is now able to serve content 7 times faster than Node.JS. While impressive, the low level technical details are not going to be my focus in this article. Instead, I will share some of my favourites among the new features and improvements. Let ‘s see whats new!

C# Code Generators

Have you ever heard of the computer viruses that can constantly rewrite themselves to avoid detection? How about building one in C#? Of course, I would never recommend anything illegal, however, with the improved support for code generation we can do this and many more interesting things. Think about complex serializers that had to be compiled in runtime to be used, making their first run awfully slow – yes XmlSerializer I am talking about you.

Think about other use cases like:

  • Building proxy classes for external services based on their metadata.
  • Building ORMs entities like entity framework does based on the existing database schema.
  • Generating new Azure functions or any other data handler classes based on some pre-defined configuration files.

Support for generators existed in some way already but with .NET 5 we will get more mainstream support for both development and deployment as well as vast toolkit that we will otherwise have to create ourselves.

Check this Visual Studio Toolbox episode for a nice introduction to generators in .NET 5.

New Language features

Top level programs

It’s a nice feature removing all the ever-present boiler plate code out of our small script, like console apps.  Basically, if you are working on a quick and relatively simple tool, there is no reason why there is so much of unnecessary semantics like default name space and program entry point. Microsoft solved this problem with a new type of project that allows you to change this:

using System;
namespace ConsoleApp87
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello Boilerplate World!");
        }
    }
}

into this:

using System;
Console.WriteLine("Hello Simple World!");

or even a one liner like this:

System .Console.WriteLine("Hi");

A little more on the subject can be found here.

Records

Classes and structs just got a new family member. Records are a new data structure making it easier for building immutable objects. This should be very useful in a lot of scenarios, such as financial domains where you may want to make your transaction records immutable. Obviously, there were ways of doing this before records but it’s just slightly easier now. “Init” keyword as shown below will make a property read only – so only assignable at object construction time.

public record Employee
{
        public string FirstName { get; init; }
        public string LastName { get; init; }
        public string Designation { get; init; }
    }

If you feel you need a bit more details on the records, check the msdn section here.

WSL2

Windows Subsystem for Linux or WSL has been tightly integrated with Visual Studio for Windows. Debug menu now has the “WSL 2” option. If you select it and press Run, your code will be executed inside the Linux distribution configured for your WSL. This helps a lot in scenarios where you are coding in Windows but your actual deployment target is Linux.  Obviously all the basic functionalities like breakpoint debugging and diagnostics will still work as if you were running it in the Windows host. The difference can be observed with a simple Environment.OSVersion which will now indicate we are in running in a Unix environment. Watch the YouTube demo here.

Project Tye – Opinionated microservices and orchestration tools

Tye is a new kind of project that solves certain DevOps(y) problems. We will talk about it in context of this official code sample – Voting App. To understand the problems that Tye solves, imagine a scenario as pictured above. Your app consists of 2 web apps, 2 different types of containerised databases, a function app and some authentication components. Setting this up to work in development and in production will be a bit challenging. There are many different endpoints and connection strings to manage, not to mention the docker containers for Redis and Postgres. So we are touching on the concepts of containerization and configuration. If you are familiar with these, great! But why does it have to be complex at all for beginners and people who are least interested in these low-level concepts.

This is exactly what Tye tries to help with. We are given a nice tye.yaml config that simplifies adding dependencies including containerized dependencies such as our databases. Tye does a lot of things for us but maybe most important is the seamless service discovery. We are given access to special extensions on the old ConfigurationManager as well as the new IConfiguration objects. The new extensions require you to register a remote service in your startup.cs file after which you will be able to load a URL for the service simply by calling:

Configuration.GetServiceUri("yourServiceDescriptionKey")
Or similarly:
Configuration.GetConnectionString("yourDatabaseDescriptionKey")

The Description keys have to match the content of your .yaml file, which is very similar to docker compose files (if you have ever worked with them). Tye uses environment variables and a well described conventions to manage your URLs and secrets in dev, staging and production. On top of a service discovery, we get a nice dashboard showing our currently loaded configuration with full access to things like streaming logs and performance counters for every single service in Tye’s scope:

Service discovery and simplified dockerized dependencies management are not the only things Tye can do for you. Once you are done coding your logic, you will have to deploy it, first locally and then perhaps to your cloud staging environment. Tye can help you in both the scenarios. It will run all your dependencies in local Docker Desktop or deploy them for you to your Kubernetes Cluster if that’s what you need.

More on how to achieve all of this in practice can be found here.

Open API – Cloud native

OpenAPI is a standard behind the Swagger tools set. What this amazing tool does for you is providing you with a standardized way of describing your API, on top of a well-described standard you will get dynamically generated test portal listing all of your public methods and objects:

No more empty “page not found” error when you run your service from visual studio! Additionally, the portal allows you to test your API methods directly from the browser – it will even display nice forms simplifying the filling request methods!

Again, this is nothing new. We were able to add Swagger support to our applications via an open source project Swashbuckle.AspNetCore for a while now but with .NET5 it has been added to all API projects by default.

Summary

I hope this article made you want to download the new 5 and check out all the new features. If that is the case, you can get it right now here. All the in-depth details going way beyond of what I have shown in this article can be found here – .NET5 MSDN page. As always, please do not hesitate to leave your comments in the box below.

Happy coding!

Author of this blog is Patryk Borowa, Aspire Systems.

Aspire Blog Team

Aspire Systems is a global technology services firm serving as a trusted technology partner for our customers. We work with some of the world's most innovative enterprises and independent software vendors, helping them leverage technology and outsourcing in our specific areas of expertise. Our services include Product Engineering, Enterprise Solutions, Independent Testing Services and IT Infrastructure Support services. Our core philosophy of "Attention. Always." communicates our belief in lavishing care and attention on our customers and employees.