How to use a controller in another assembly in ASP.NET Core MVC 2.0?
For the sake of modularity, I have created some controllers in different assemblies. Each assembly represents a bounded context (a module, a sub-system, a division, etc.) of the overall system.
Each module's controllers are developed by someone that knows nothing about other modules, and a central orchestrator is about to cover all these modules in one single application.
So, there is this module called school, and it has a TeacherController
in it. The output of it is Contoso.School.UserService.dll
.
The main orchestrator is called Education
and it has a reference to Contoso.School.UserService.dll
.
My program.cs
is:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args).UseKestrel()
.UseStartup<Startup>()
.Build();
Yet for the routes of teacher controller, I get 404. How to use controllers in other assemblies?
Inside the ConfigureServices
method of the Startup
class you have to call the following:
services.AddMvc().AddApplicationPart(assembly).AddControllersAsServices();
Where assembly
is the instance Assembly
representing Contoso.School.UserService.dll
.
You can load it either getting it from any included type or like this:
var assembly = Assembly.Load("Contoso.School.UserService");
For .NET Core 3.0 the API has been slightly changed and the easiest way to register controllers from external assembly in Startup.cs
looks like:
public void ConfigureServices(IServiceCollection services)
{
var assembly = typeof(**AnyTypeFromRequiredAssembly**).Assembly;
services.AddControllers()
.PartManager.ApplicationParts.Add(new AssemblyPart(assembly));
}
I'm trying to resolve the controllers while migrating legacy unit tests from .NET Framework to aspnet core 3.1, this is the only way I got it working:
var startupAssembly = typeof(Startup).Assembly;
var services = new ServiceCollection();
// Add services
...
// Add Controllers
services
.AddControllers()
.AddApplicationPart(startupAssembly)
.AddControllersAsServices();
If I change the order of the three last lines it does not work.
Avoid doing this for unit testing unless you really have to, i.e. for legacy reasons. If you are not working with legacy code you are probably looking for integration tests.