Plugin Architecture in ASP.NET Core – How To Master It
Tags: dotnet, csharp, webdev, programming
Published: 2023-08-03 11:00:00

### Introduction

In the ever-evolving world of software development, flexibility and extensibility are key. As developers, we constantly strive to write code that not only solves the problem at hand but also accommodates future changes and enhancements. This can [lead us down a path of over-engineering](https://medium.com/r/?url=https%3A%2F%2Fyoutu.be%2FbexmWsnYCEU), for sure, so it’s important that we be aware of this! However, this is where a plugin architecture comes into play, especially in the context of [ASP.NET Core](https://medium.com/r/?url=https%3A%2F%2Fwww.devleader.ca%2Ftag%2Fasp-net-core%2F).

NOTE: This blog post was [originally posted here in full](https://medium.com/r/?url=https%3A%2F%2Fwww.devleader.ca%2F2023%2F07%2F31%2Fplugin-architecture-in-asp-net-core-how-to-master-it%2F).

In this blog post, we will delve into the [world of plugins](https://medium.com/r/?url=https%3A%2F%2Fwww.devleader.ca%2Ftag%2Fplugins%2F), exploring how they can be leveraged in ASP.NET Core to create more flexible and maintainable applications. We’ll walk through some [C# code samples](https://medium.com/r/?url=https%3A%2F%2Fwww.devleader.ca%2Ftag%2Fsamples%2F), discuss the pros and cons of such a design, and even touch on how to use the [Autofac NuGet package](https://medium.com/r/?url=https%3A%2F%2Fwww.devleader.ca%2Ftag%2Fautofac%2F) to load plugins. So, whether you’re a seasoned C# programmer or a curious beginner, buckle up for an exciting journey into the world of plugins!

### What is a Plugin Architecture?

A plugin architecture, also known as a plug-in or extension model, is a design pattern that allows a software application to be extended with new features or behaviors at runtime. This is achieved by defining a set of interfaces or abstract classes that can be implemented by third-party components, which are loaded and executed dynamically by the host application.

When you’re thinking about your plugin architecture, it doesn’t necessarily have to be something that is exposed to others (i.e. a truly public API). This can be highly dependent on your situation. For example, I use plugins even for my own personal projects where nobody else will be contributing. I have used plugin architectures where other teams in my organization (and potentially beyond) can extend part of the offering. I have also used plugin architectures for allowing completely third-party individuals to extend a code base’s functionality.

### Why Use a Plugin Architecture in ASP.NET Core?

ASP.NET Core is a robust, open-source framework for building modern web applications. It’s known for its high performance, flexibility, and extensibility. By leveraging a plugin architecture in ASP.NET Core, we can take these benefits to the next level.

Many of the new resources we see coming out showcasing examples like minimal APIs often illustrate very simplistic applications. For example, even the weather app sample project that is offered by Microsoft illustrates a basic API where an extension of this likely looks like copy-pasting routes to tack on some extra features. But when you start considering extensibility into other domains and separating these things out, the idea of a plugin architecture starts to fit in better.

Let’s check out some of the pros and cons of using a plugin architecture. This is by no means a conclusive list:

### Pros

1.  **Flexibility and Extensibility:** A plugin architecture allows you to add, remove, or update functionality without modifying the core application code. This makes your application more flexible and easier to maintain and extend.
2.  **Separation of Concerns:** Each plugin encapsulates a specific functionality, promoting a clean separation of concerns and making your code more modular and easier to test.
3.  **Collaboration and Scalability:** A plugin architecture facilitates collaboration, as different teams can work on different plugins simultaneously. It also supports scalability, as new plugins can be added as your application grows.

### Cons

1.  **Complexity:** Implementing a plugin architecture can add complexity to your application, especially when dealing with plugin dependencies and versioning.
2.  **Performance Overhead:** Dynamically loading and unloading plugins can introduce performance overhead. However, this is often negligible compared to the benefits. This is something that needs to be considered situationally!
3.  **Security Risks:** Plugins can pose security risks if they are not properly isolated and sandboxed. If the APIs are designed poorly, they may give too much access to the core of the system. Even if not “security” necessarily, poorly designed plugin APIs may allow implementations to abuse the access they have against the intended design.

### Leveraging a Plugin Architecture in ASP.NET Core: A Practical Example

Let’s dive into some code. We’ll use the Autofac NuGet package to load our plugins. Autofac is a popular inversion of control (IoC) container for .NET, known for its flexibility and performance.

Here’s a simple example of a plugin loader using Autofac:

```
public sealed class RoutesModule : Module  
{  
    protected override void Load(ContainerBuilder builder)  
    {  
        // this code looks for all plugins that are marked as being  
        // discoverable, which is indicated by the attribute:  
        // DiscoverableRouteRegistrarAttribute  
        var discoverableRouteRegistrarTypes = CalorateContainerBuilder  
            .CandidateAssemblies  
            .SelectMany(x => x  
                .GetTypes()  
                .Where(x => x.CustomAttributes.Any(attr => attr.AttributeType == typeof(DiscoverableRouteRegistrarAttribute))))  
            .ToArray();  
  
        foreach (var type in discoverableRouteRegistrarTypes)  
        {  
            builder.RegisterType(type).SingleInstance();  
        }  
  
        builder  
            .Register(c =>  
            {  
                var app = c.Resolve<WebApplication\>();  
                foreach (var registrar in discoverableRouteRegistrarTypes  
                    .Select(x => c.Resolve(x))  
                    .Cast<IRouteRegistrar\>())  
                {  
                    // the implementation of the Register method  
                    // in this case gives the plugin owner a TON  
                    // of flexibility to register routes, groups,  
                    // etc... in your situation you may want to  
                    // restrict this further  
                    registrar.Register(app);  
                }  
  
                // NOTE: this is just a marker type that I use  
                // in my applications to control when certain  
                // types of plugins will be loaded. for example,  
                // all of these plugins will only be loaded when  
                // the core application tries to resolve all of  
                // the instances of PostBuildWebApplicationDependency.  
                return new PostBuildWebApplicationDependency(GetType());  
            })  
            .AsImplementedInterfaces()  
            .SingleInstance();  
    }  
}
```

In this code, we’re defining a module that scans assemblies for types marked with the `DiscoverableRouteRegistrarAttribute` attribute. These types are registered with Autofac as single instances. Then, we register a `PostBuildWebApplicationDependency` that resolves all the discovered route registrars and calls their `Register` method.

Check out this video for a walkthrough on how I leverage this pattern for working on vertical slices in my ASP.NET Core application:

{% embed https://youtu.be/5OKLiQM2y30 %}

### Deep Dive into Plugin Architecture

If you’ve enjoyed this post so far, check out [the full blog article where I describe more about plugin architecture](https://medium.com/r/?url=https%3A%2F%2Fwww.devleader.ca%2F2023%2F07%2F31%2Fplugin-architecture-in-asp-net-core-how-to-master-it%2F)! Thank you for reading, and if you’d like to keep up to date with my content you can [subscribe to my weekly newsletter](https://medium.com/r/?url=https%3A%2F%2Fbit.ly%2FDevLeaderWeekly) where I provide a quick 5-minute read every weekend on software engineering and dotnet topics!