Mulciber Coder
Mulciber Coder

Reputation: 127

ASP.NET Core parameter injection based on Route parameter

I'm not sure if this is even possible, but I would like a Route-parameter to determine the type of object that is injected into my controller.

Basically, the code should look like this:

public interface IConfig { String value{ get;set;} } 
public class ConfigA : IConfig { ... } 
public class ConfigB : IConfig { ... } 


    [Route("monitor/v{version:apiVersion}/blacklist")]
    [ApiController]
    public class BlackListController : ControllerBase
    {
    
      private IConfig _config;      

      public BlackListController (IOptions<IConfig> config) 
      {
         _config = config.Value;
      }
      // if route is /monitor/v1/blacklist then configshould be an instance of ConfigA 
      // if route is /monitor/v2/blacklist then config should be an instance of ConfigB
    
    }

Upvotes: 0

Views: 500

Answers (1)

Dmitry Grebennikov
Dmitry Grebennikov

Reputation: 434

You can't do it natively. If you want to use different interface implementations depending from rout you must need to implement your own dependency resolver and add it to DI container.

Example code:

 public delegate IConfig Resolver(ConfigType key);
 services.AddSingleton<Resolver>(serviceProvider => key =>
        {
            return key switch
            {
                ConfigType.ConfigA => serviceProvider.GetService<ConfigA>(),
                ConfigType.ConfigB => serviceProvider.GetService<ConfigB>(),
                _ => serviceProvider.GetService<DefaultConfig>(), //default: in switch
            };
        });

Upvotes: 1

Related Questions