In a current WebApi project I have a generic controller:
public class EntityController<T>
where T : Entity { }
It's created at runtime with a specified type if the controller name in the route matches a type name.
For example: /api/user/
initialises controller EntityController<User>
.
To accomplish this, I'm using a custom ControllerSelector:
internal class ControllerSelector : DefaultHttpControllerSelector
{
... other members omitted for clarity
public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
string controllerName = base.GetControllerName(request);
HttpControllerDescriptor descriptor;
Type controllerType = typeof(EntityController<>).MakeGenericType(_entityTypes[controllerName]);
descriptor = new HttpControllerDescriptor(_configuration, controllerName, controllerType);
_descriptorCache.TryAdd(controllerName, descriptor);
return descriptor;
}
... other members omitted for clarity
}
It appears this method is not going to work in .Net Core.
I've found and tried these examples but they don't appear to solve my problem:
- This question simply changes the route values.
- This question prints out the controller names have already been loaded (but the title suggests it's what I need).
- Another question suggested creating instances of all the possible generic controllers so they could be picked up by the dependency registration engine but this doesn't feel right.
- Other questions started pointing to towards a custom IRouter but the implementations seemed far too convoluted for what was easily achieved in the previous version.
So, using .Net Core, how can I control the creation of controllers to create a generic controller on the fly?