Plugin Mechanism with Parts in ASP.NET Core

Plugin Mechanism with Parts in ASP.NET Core

A plugin-like mechanism is already built into ASP.NET Core, and is called Parts or Application Parts.

In principle, it is a discovery mechanism to be able to use Razor or MVC components such as controllers from other assemblies, for example. Therefore, Application Parts are also particularly well suited for Domain Driven Design (DDD) separation of application components in ASP.NET Core. A DDD abstraction is the most used way of these Application Parts in my applications and architectures.

The DDD Logic Assembly

As in an otherwise clean separation of responsibilities, we keep the logic in an extra project that becomes an extra assembly.

This assembly has no information that ASP.NET Core is the runtime!

The ASP.NET Core Part Assembly

The Part Assembly is an extra project that gets a reference to ASP.NET Core.

<Project Sdk="Microsoft.NET.Sdk">


    <ItemGroup>
        <FrameworkReference Include="Microsoft.AspNetCore.App" />
    </ItemGroup>

In this project (e.g. MyCompany.MySuite.MyFeature) we can now create our controllers.

// MyCompany.MySuite.MyFeature.AspNetCore

public class PartPingController : Controller
{
    [HttpGet]
    [Route("mypart/ping"]
    public IActionResult Ping()
    {
        return Ok(DateTimeOffset.UtcNow);
    }

The Registration

The registration of the application part must now be done within the configuration of the application, namely within the MVC configuration.

Thereby the MvcBuilder is created. The assemblies in which it is to search for parts, must now be made known to it.

// MyCompany.MySuite.MyWebApp
public void ConfigureServices(IServiceCollection services)
{
    // register mvc controller
    IMvcBuilder mvcBuilder = services.AddControllers()

    // register application parts
    mvcBuilder.AddApplicationPart(typeof(PartPingController).Assembly);
}

Done. That's how easy it is to use Application Parts in ASP.NET Core to keep the hosting project itself lean and use Parts for plugins and routing separation.