Can I make an ASP.NET Core controller internal?

后端 未结 2 1637
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-04 22:03

ASP.NET (and Core) controllers need to be public.

Problem is I have a controller which depends (in its constructor) on something internal.

相关标签:
2条回答
  • 2021-01-04 22:36

    Sou you have this (it always helps to include a MCVE in your question):

    internal class FooDependency
    {
    
    }
    
    public class FooController
    {
        public FooController(FooDependency dependency)
        {
            // ...
        }
    }
    

    And you can't make FooDependency public, but you need FooController to be public?

    Then you need to apply a public interface to the internal dependencies:

    public interface IFooDependency
    {
    
    }
    
    internal class FooDependency : IFooDependency
    {
    
    }
    
    public class FooController
    {
        public FooController(IFooDependency dependency)
        {
            // ...
        }
    }
    
    0 讨论(0)
  • 2021-01-04 22:57

    If you want to include internal controllers, you can provide your own implementation of the ControllerFeatureProvider class which is responsible for determining whether a type is a controller or not. In the following example I have created an implementation that looks for controllers implementing a custom base class and falling back to the default implementation for all other cases. In this case, the custom controllers will be discoverable despite being internal, while all other controllers will not.

    class CustomControllerFeatureProvider : ControllerFeatureProvider
    {
        protected override bool IsController(TypeInfo typeInfo)
        {
            var isCustomController = !typeInfo.IsAbstract && typeof(MyCustomControllerBase).IsAssignableFrom(typeInfo);
            return isCustomController || base.IsController(typeInfo);
        }
    }
    

    and to register it:

    services.AddMvc().ConfigureApplicationPartManager(manager =>
    {
        manager.FeatureProviders.Add(new CustomControllerFeatureProvider());
    });
    

    You should probably take a look at the implementation of IsController to see how ASP.NET handles edge cases around the types.

    0 讨论(0)
提交回复
热议问题