Search code examples
c#autofac

Register same interface multiple times - Autofac


I'm trying to register an interface with different config as below:

private static ContainerBuilder RegisterAzureStorage(this ContainerBuilder containerBuilder, IAzureStorageOptions azureStorageOptions)
    {
        containerBuilder.Register(c =>
                new AzureStorageKeyValuePersistenceService(
                    new AzureStorageKeyValuePersistenceConfig(
                        azureStorageOptions.DctAzureBlobConnectionString,
                        azureStorageOptions.DctAzureBlobContainerName)))
            .As<IStreamableKeyValuePersistenceService>()
            .Keyed<IStreamableKeyValuePersistenceService>(PersistenceStorageKeys.DctAzureStorage)
            .SingleInstance();

        containerBuilder.Register(c =>
                new AzureStorageKeyValuePersistenceService(
                    new AzureStorageKeyValuePersistenceConfig(
                        azureStorageOptions.NcsAzureBlobConnectionString,
                        azureStorageOptions.NcsAzureBlobContainerName)))
            .As<IStreamableKeyValuePersistenceService>()
            .Keyed<IStreamableKeyValuePersistenceService>(PersistenceStorageKeys.NcsAzureStorage)
            .SingleInstance();

        return containerBuilder;
    }

Then in my constuctor:

public ReportingController(
        [KeyFilter(PersistenceStorageKeys.DctAzureStorage)] IStreamableKeyValuePersistenceService dctStorage,
        [KeyFilter(PersistenceStorageKeys.NcsAzureStorage)] IStreamableKeyValuePersistenceService ncsStorage)
    {
        _dctStorage = dctStorage;
        _ncsStorage = ncsStorage;
    }

And the Usage:

await _dctStorage.SaveAsync(........);
await _ncsStorage.SaveAsync(........);

However, when executing it's only picking up the last registration and saving both objects to the same location.

I can get it to work using the enumerable method:

public ReportingController(IEnumerable<IStreamableKeyValuePersistenceService> storage)
    {
        _storage = storage;
    }

and then for eaching over the enumerable, but I would prefer to use the keyed method if possible.

Any ideas on what I'm missing?


Solution

  • For anyone who comes across this issue in the future I was missing a registration, the executing interface in this case IReportingController needs to be registered with the WithAttributeFiltering() as below:

    containerBuilder.RegisterType<ReportingController>().As<IReportingController>().WithAttributeFiltering();