Over a million developers have joined DZone.

Loading Web API Controllers from a separate library when Self Hosting Web API

·

When self hosting Web API, we have to create controllers on
the same project, otherwise it does not detect the libraries even if we
reference the Web API project where we have all the controllers and classes
defined.

For example, if we have a Web API project that was hosted
over IIS earlier, and we decided to self host it on a Windows service project or
a console application, we have to copy-paste or drag/drop the classes from the
Web API project to self host the Web API project and also have to change its
namespace so it could be searchable by the Web API framework. But what if we
have a centralized project where we have all the controllers in place and we
want the self hosted Web API project to load all the controllers from there.

In order to overcome this scenario, we can create a custom
assembly resolver to say SelfHostAssemblyResolver and replace the default one with
this. SelfHostAssemblyResolver should be derived from IAssemblyResolver and
then implement the GetAssemblies method that loads the assemblies from
particular path.

So first, create a custom assembly resolver


In the below code, where you are initializing the Self Host Web API,
replace the default assembly resolver with your custom assembly resolver using
HttpSelfHostConfiguration object.


In the above code snippet, DemoWebApi.dll is the main Web
API project I was using initially, that had used the default Web API hosting on
IIS.

Happy coding!



Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}