4

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?

Community
  • 1
  • 1
Phil Cooper
  • 3,083
  • 39
  • 63
  • Did you ever find a way of doing this? – Andrew Davis Mar 04 '17 at 00:58
  • @AndrewDavis sadly no, I didn't. It was a PoC porting exercise which I abandoned. Looking back at the options available to me, the most achievable was to create all the possible controller types and register them with a DI container. If you find a way, please add an answer! – Phil Cooper Mar 04 '17 at 07:27
  • I have gone through the stack trace, replacing the the parts I can via the IoC container. It appears that the issue in the `ObjectMethodExecutor` which can't be swapped out. – Andrew Davis Mar 04 '17 at 09:15

0 Answers0