Tuesday, June 29, 2021

Can we have WebAPI controllers in different assemblies?

The question is clear from the title itself. Let us put the environment details to get more clarity.

Problem

It is an ASP.Net Core 2.1 Web API application that runs on .Net Framework 4.8. It has its own controller classes in its assembly. In addition to that, there are some controller classes in other projects that need to be added via the nuget package manager. Assuming they are not conflicting.

This was not supported out of the box prior to ASP.Net Core 2.1 where we have to inherit our web API controller classes from the base APIController class. We had to do something with the ControllerBuilder class or inherit the IAssemblyResolver class. Something complex.

Solution

With ASP.Net Core 2.1, there is no need to complicate things as long as we are inheriting the controller class from the ControllerBase class and decorate it with [ApiController].

We have to make sure the other assembly that contains the controller classes is available in /bin folder of the hosting application. If not in the /bin folder it's reachable to be loaded into the application.

Sample

It's not complete by just telling it is simple. A working solution can be downloaded from GitHub. It has a readme.md file to get started.

Points to note

When we have multiple controller assemblies, we need to make sure the controllers are not conflicting with each other.

APIController v/s ControllerBase

Now there may be a question arising. What is the difference between these APIController v/s ControllerBase classes for ASP.Net WebAPI? Tune for a dedicated blog post on it. Wait it's something that happened years back. Why should there be one more blog post? The answer is right there in StackOverflow.  Below are the main points.

For more details refer to the official Microsoft link that explains the MVC and WebAPI merge.

No comments: