arnoldrob
arnoldrob

Reputation: 31

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.

Upvotes: 3

Views: 8495

Answers (2)

andrecarlucci
andrecarlucci

Reputation: 6296

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());

Upvotes: 9

Van
Van

Reputation: 1387

  • 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

Upvotes: 3

Related Questions