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, for sure, so we must be aware of this!
However, this is where a plugin architecture comes into play, especially in the context of ASP.NET Core.
In this blog post, we will delve into the
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.
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:
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:
Now that we’ve covered the basics, let’s take a deeper dive into the plugin architecture. We’ll look at how plugins can be designed, how they interact with the host application, and how they can be managed and loaded at runtime.
When designing a plugin, the first step is to define the interface or abstract class that the plugin will implement. This interface serves as a contract between the plugin and the host application, specifying what methods and properties the plugin must provide.
For example, in an e-commerce application, you might have an IPaymentGateway
interface that defines methods for processing payments, issuing refunds, and checking transaction status. Each payment gateway (e.g., PayPal, Stripe, etc.) would then implement this interface as a separate plugin.
Plugins can interact with the host application in various ways. For example, they can:
In reality, leveraging plugins allows you to explore the different functionality that you want to have exposed and be extensible. The limit is your own imagination!
Managing and loading plugins at runtime can be a complex task, but libraries like Autofac can help simplify this process. With Autofac, you can easily register and resolve plugins, and even manage their lifetime (i.e., when they are created and destroyed). In the code sample above, we used Autofac to register all types marked with the DiscoverableRouteRegistrarAttribute
attribute as single instances. Then, we resolved these instances and called their Register
method to register their routes with the application.
You can accomplish this in many different ways depending on the needs of your application and how you would like your plugin interactions to work. The discoverable pattern mixed with automatic registration and resolution works really well for me. You may need something more structured to control order or impose other restrictions, so keep this in mind!
Here are two additional videos on using Autofac to load plugins!
A plugin architecture can be a powerful tool in your ASP.NET Core development toolkit. It offers flexibility, promotes a clean separation of concerns, and facilitates collaboration and scalability. However, it also comes with its challenges, such as added complexity, potential performance overhead, and security risks. Personally, I create nearly every project I jump into with some amount of plugin architecture in mind. While this may not make sense for everyone, the tools at our disposal to dynamically load new functionality are too powerful for me to ignore!
By understanding these trade-offs and leveraging tools like Autofac, you can harness the power of plugins to build more flexible, extensible, and maintainable ASP.NET Core applications. Plugin architectures are one of my favorites for ensuring these traits for your projects.
For more insights into ASP.NET Core, C#, and software development in general, feel free to check out my
This blog post was