ASP.NET Core - Controllers in referenced assemblies

Viewed 238

I got a common library for .NET Core 3.1, in which I created a WEB API controller intended for sharing with multiple applications.

In order to add this to an application, I expected to something like this (from 3.0):

services.AddControllers()
        .PartManager.ApplicationParts.Add(new AssemblyPart(assembly));

However, if I simply reference the common project, and call services.AddControllers(), the controller get added automagickally.. which is kinda spooky. Apparently, AddControllers() traverses every assembly in all referenced projects, and just stupidly adds every controller it finds along the way.

I can't find documentation on this behaviour. The only way I can see to control this, is to create another project with the controller, and reference it when needed.

What's the correct (or intended) way of doing this ?

1 Answers

I suspect that the intended/correct way of doing this is to not reference projects with controllers with other projects with controllers (even if you reference a project that references a project with a controller etc.).

i.e. any business logic should be referenced by both web api's seperately in something like a class library.

If you do arrive in this situation a work around is as follows;

services.AddControllers().ConfigureApplicationPartManager(o =>
            {
                o.ApplicationParts.Clear();
                o.ApplicationParts.Add(new AssemblyPart(typeof(Startup).Assembly));
            });

Where Startup is referencing the class you are in.

There is probably a slightly different way to handle it in .NET 6.

Related