Question

For one on my unit test I am developping a linq query that retrieves all the controllers types from a MVC project and make sure it inherits from a BaseController.

var controllers = typeof(MvcApplication).Assembly.GetTypes().Where(typeof(IController).IsAssignableFrom);

How can I remove from this list the BaseController object? I have tried several things but it always remove from the list all the controllers that do not inherits from BaseController.

Here is the unit test

[Fact]
    public void All_Controllers_Inherit_From_BaseController()
    {
        var controllers = typeof(MvcApplication).Assembly.GetTypes().Where(typeof(IController).IsAssignableFrom);

        foreach (var controller in controllers)
        {
            Assert.True(controller.BaseType == typeof(BaseController));
        }
    }

Thanks!

Was it helpful?

Solution

Well, two options spring to mind:

  • Explicitly "remove" BaseController using Except:

    var controllers = typeof(MvcApplication).Assembly
                              .GetTypes()
                              .Except(new[] { typeof(BaseController) })
                              .Where(typeof(IController).IsAssignableFrom);
    
  • Only consider concrete types; I assume BaseController is abstract:

    var controllers = typeof(MvcApplication).Assembly
                              .GetTypes()
                              .Where(type => !type.IsAbstract)
                              .Where(typeof(IController).IsAssignableFrom);
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top