简体   繁体   中英

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?

对于将来遇到此问题的任何人,我都缺少注册,在这种情况下IReportingController需要使用WithAttributeFiltering()注册执行接口,如下所示:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM