Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c# - Can I make an ASP.NET Core controller internal?

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

Problem is I have a controller which depends (in its constructor) on something internal. And that dependency depends on something internal, which depends on something internal, etc. So I need to make the controller internal as well.

But then it won't be discovered by the controller factory.

Is there a way to make an internal controller discoverable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...