Search code examples
.net-coredependency-injectionazure-sdk-.net

Azure SDK for .Net - dependency injection for two subscriptions


I have the following code that registers an instance to the .net services collection for Azure services.

services.AddSingleton(x => Microsoft.Azure.Management.Fluent.Azure.Authenticate(azureCredentials)
             .WithSubscription(Configuration[ConfigurationConstants.AzureAuth_SubscriptionId]));

This code then resolves an instance of the IAzure in my service class where I can access all the services available like _azure.SqlServers.ListAsync etc.

I want to have a way so I can work with two Azure subscriptions and thus register two instances to the services collection and then be able to resolve the one that I want. You can check here for a similar example of what I want, it's about the blob storage though.


Solution

  • As with the linked example, you would need a way to uniquely differentiate the services and most likely need to use a factory pattern design

    public interface IAzureFactory {
        IAzure GetSubscription(string subscriptionId);
    }
    

    The subscription Id could be used to separate the services, but that would require getting the current subscription id from the service to find the match

    public class AzureFactory : IAzureFactory {
        private readonly IEnumerable<IAzure> subs;
    
        public AzureFactory (IEnumerable<IAzure> subs) {
            this.subs = subs;
        }
    
        public IAzure GetSubscription(string subscriptionId) {
            return subs.FirstOrDefault(_ => _.SubscriptionId == subscriptionId) ??
                throw new InvalidArgumentException("invalid subscription Id)"; 
        }
    }
    

    From there it is only a matter of registering the different subscriptions.

    services.AddSingleton<IAzureFactory, AzureFactory>();
    
    services
        .AddSingleton(x => Microsoft.Azure.Management.Fluent.Azure.Authenticate(azureCredentials)
             .WithSubscription(Configuration[ConfigurationConstants.AzureAuth_SubscriptionId1]));
    
    services
        .AddSingleton(x => Microsoft.Azure.Management.Fluent.Azure.Authenticate(azureCredentials)
             .WithSubscription(Configuration[ConfigurationConstants.AzureAuth_SubscriptionId2]));
    

    And using the factory to get the desired subscription

    //...
    
    private readonly IAzure azure;
    
    //ctor
    public MyService(IAzureFactory factory) {
        azure = factory.GetSubscription(...);
    }
    
    //...