Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally remove controller from being registered by ASP.NET Core and added to ServiceCollection

We have ASP.NET Core solution with standard Microsoft.Extensions.DependencyInjection and need to register certain control depending on configuration setting.

Some Example ApiController that inherits from ControllerBase and all their related actions should only be registered if certain bool is true.

Is this possible? I looked at services.AddMvc() but I didn't see any option that would easily allow me to either:

  • Prevent certain ExampleController from being registered
  • Remove ExampleController and all it's related actions from IServiceCollection after being registered
like image 554
nikib3ro Avatar asked Jan 07 '20 06:01

nikib3ro


1 Answers

As pointed out in comments, implement feature filter and register it in your services config:

public class MyFeatureProvider: ControllerFeatureProvider
{
    private readonly bool condition;

    public MyFeatureProvider(bool condition)
    {
        this.condition = condition;
    }
    
    protected override bool IsController(TypeInfo typeInfo) 
    {
        if (condition && typeInfo.Name == "ExampleController") 
        {
            return false;
        }
        return base.IsController(typeInfo);
    }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {            
        services.AddMvc().ConfigureApplicationPartManager(mgr => 
        {
            mgr.FeatureProviders.Clear();
            mgr.FeatureProviders.Add(new MyFeatureProvider(true));
        });            
    }
}

I'll link the source code in case you'd like to check out stock standard implementation and see how it works for reference

like image 64
timur Avatar answered Nov 05 '22 06:11

timur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!