Recently I built plug-ins support for my TemperatureStation IoT solution website. The code for .NET Core is different from what we have seen on full .NET Framework (application domains etc.) but there’s still nothing complex. This blog post describes how to build simple plug-ins support for ASP.NET Core web applications.

After some searching in web and some small experimenting I came out with a simple solution that covers the following:

Loading types from assemblies

Registering types automatically with built-in dependency injection

Getting instances through built-in dependency injection

The code shown here is also kind of experimental and it is taken from my open-source IoT solution called TemperatureStation.

Calculator Plug-ins

TemperatureStation has plug-ins called Calculators. Calculators are classes that can be bound to measurements and when readings are reported then Calculators are run on readings. They provide different calculations like finding freezing point of liquid, estimating the time it takes for liquid to get to freezing point etc.

Finding Plug-in Types

To detect plug-ins I wrote the CalculatorsLoader class. This a static class that creates a list of calculator types. The rule is simple: the class must implement ICalculator interface and must have CalculatorAttribute. Consider this class as an internal matter of the application.

Automatic Registering of Plug-in Types

To use ASP.NET Core dependency injection I wrote a class that provides extension method for IServiceCollection. Dependency injection is needed because Calculators may use constructor injection to access services and database.

When web application starts then ConfigureServices method is called and Calculators are automatically registered.

Plug-in Provider

To access calculators I wrote ICalculatorProvider interface and CalculatorProvider class. This class with CalculatorExtensions are the only classes that access CalculatorsLoader directly. All other classes in system use provider to query the calculator types. ICalculatorProvider is introduced to ASP.NET Core dependency injection in application Startup class.

The real usage in my solution is more complex but this example gives the point.

Wrapping Up

On .NET Core, things work a little bit differently compared to the full .NET Framework. Although this solution is not perfect, it was still pretty easy to find information and make the code work. It was also easy to automatically register plug-in types with ASP.NET Core framework-level dependency injection and come out with simple classes that architecturally fit into a web application. For my IoT system, this solution is good enough to go with for today.