How to use a controller in another assembly in ASP.NET Core MVC 2.0?

前端 未结 5 1827
一整个雨季
一整个雨季 2020-12-01 06:16

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

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 06:56

    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.

提交回复
热议问题