Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net WebApi: How to load additional controllers at runtime

in my Asp.Net MVC 4 WebApi application I want to load additional WebApiControllers dynamically at a later time (after the WebApi initialization), which are in separate assemblies. Furthermore I want to add routes for those controllers at runtime.

I am wonder, if this is possible to do.

My goal is to build a web-app, where I can upload controllers (compiled assemblies) and the controllers will be automatically hosted within this application.

I've already tried to achieve that by implementing my own AssemblyResolver class, but (as far as I have seen), the AssemblyResolver is loaded once at initialization phase.

May be there is an option to "re-load" all controllers.

Any help will be appreciated!

Marius

like image 244
Marius Avatar asked Nov 27 '12 08:11

Marius


People also ask

Which service is used for adding controller in Web API?

ASP.NET Core supports creating web APIs using controllers or using minimal APIs.

What is the best controller for all Web API controllers to inherit from?

It's recommended that API controllers in ASP.NET Core inherit from ControllerBase and add the [ApiController] attribute. Standard view-based MVC controllers should inherit from Controller . In both frameworks, controllers are used to organize sets of action methods.

How many get methods we can implement in single controller in Web API?

Usually a Web API controller has maximum of five actions - Get(), Get(id), Post(), Put(), and Delete().


2 Answers

You could use Web API Dependency Resolver:

public class WebApiApplication : System.Web.HttpApplication
{
    void ConfigureApi(HttpConfiguration config)
    {
        config.DependencyResolver = new MyDependencyResolver();
    }

    protected void Application_Start()
    {
        ConfigureApi(GlobalConfiguration.Configuration);

        // ...
    }
}

Using the Web API Dependency Resolver

like image 83
maximpa Avatar answered Sep 22 '22 23:09

maximpa


Thanks for your answers.

I figured it out, it is not possible to do that, since all of the controllers are loaded once and are cached all over the time.

See HttpControllerTypeCache in DefaultHttpControllerSelector method InitializeControllerInfoCache(...).

In oder to do a type-cache refresh, I have to implement a custom HttpControllerSelector.

like image 33
Marius Avatar answered Sep 22 '22 23:09

Marius