Asp Net Core 2.0 MVC: how to use a Controller of an external assembly

It is a good practice to keep projects separate according to their logic.
A solution of a web project could be divided into:

  • ClientProject
  • ControllerProject
  • DataAccessProject
  • TestProject

The client is the startup project. To make sure that it is possible to use the ControllerProject classes (so located in an external assembly), in the Startup.cs of the ClientProject:

public IServiceProvider ConfigureServices(IServiceCollection services) 
{
    // Add external reference to MVC controller
    services.AddMvc().AddApplicationPart(
        typeof(MyController).GetTypeInfo().Assembly)
        .AddControllersAsServices();
    // Other code...
}

With these few simple instructions we can make sure that our project ClientProject can uses the controller class MyController located in the external project ControllerProject.

Leave a comment