Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Web API Controller to different assembly

How can I add Web Api Controller to a different assembly? I want to separate the web API controllers from my MVC application.

like image 804
arnoldrob Avatar asked Nov 28 '25 16:11

arnoldrob


2 Answers

WebApi does that out the box.

The DefaultAssembliesResolver class is the one used to load the assemblies to look for ApiControllers. Here is the source code:

  public class DefaultAssembliesResolver : IAssembliesResolver {    
    public virtual ICollection<Assembly> GetAssemblies() {
      return AppDomain.CurrentDomain.GetAssemblies().ToList();
    }
  }

The trick is to load your assembly to the AppDomain before the first call to a web.api service.

Call any method of a class in the target assembly or simply load a type from it. Ex:

var x = typeof (YourApiControllerInAnotherAssembly);

If you're using an older version of WebApi, try implementing IAssembliesResolver and changing the default implementation of it like this:

GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), 
                                                   new YourCustomAssemblyResolver());
like image 79
andrecarlucci Avatar answered Dec 01 '25 04:12

andrecarlucci


  • create a new class library project in your solution and add new classes that inherit from ApiController.
  • you may have to add some extra references to your new project as all the mvc libraries are not included by default.
  • in your mvc project, add a reference to the new class library project that contains your api controllers
  • build and test
like image 30
Duy Avatar answered Dec 01 '25 05:12

Duy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!