Web API 2 Is it possible to load a route/controller programmatically?

China☆狼群 提交于 2019-12-03 14:05:58

Okay, so after much research... I have tracked down the proper class to override, and can now per-request check whether or not the controller was able to be resolved, and if not, attempt to load the proper assembly into memory (based on controller name at the moment), and return the associated controller.

Here is the code:

public class CustomHttpControllerSelector : DefaultHttpControllerSelector {
  private readonly HttpConfiguration _configuration;

  public CustomHttpControllerSelector(HttpConfiguration configuration) : base(configuration) {
    _configuration = configuration;
  }

  public override HttpControllerDescriptor SelectController(HttpRequestMessage request) {
    HttpControllerDescriptor controller;
    try {
      controller = base.SelectController(request);
    }
    catch (Exception ex) {
      String controllerName = base.GetControllerName(request);
      Assembly assembly = Assembly.LoadFile(String.Format("{0}pak\\{1}.dll", HostingEnvironment.ApplicationPhysicalPath, controllerName));
      Type controllerType = assembly.GetTypes()
        .Where(i => typeof(IHttpController).IsAssignableFrom(i))
        .FirstOrDefault(i => i.Name.ToLower() == controllerName.ToLower() + "controller");
      controller = new HttpControllerDescriptor(_configuration, controllerName, controllerType);
    }
    return controller;
  }
}

and of course you'd need to replace the service in the WebApiConfig's Register method file as such:

config.Services.Replace(typeof(IHttpControllerSelector), new CustomHttpControllerSelector(config));

There is definitely more work to be done here, but this is a good start. It allows me to dynamically add controllers to the hosting website while it's up and running, without requiring an outage.

The main issue with this code obviously is that the newly loaded controller isn't added to the list of registered controllers, so the exception is always thrown and handled on every request (for those controllers). I'm looking into whether or not I can add it to the registered list in some way, so we'll see where this leads.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!