0

Is it possible to resolve multiple instances of the same service registered for an interface but constructed with different parameters?

For example, I have a Interface and Service:

public interface INotificationService
{
    Task PublishAsync(string message);
    Task PublishAsync(string subject, string message);
}

and a class that implements that interface

public class SnsNotificationService : INotificationService
{           
    public SnsNotificationService(
        string topicArn,
        ILogger<SnsNotificationService> logger,
        IAmazonSimpleNotificationService client) { }
}

Registered like:

builder.RegisterType<SnsNotificationService>().As<INotificationService>()
        .WithParameter("topicArn", _configuration.TopicArn);

My consuming service gets INotifiicationService injected into its constructor.

public class InstanceStateManager
{                         
     public InstanceStateManager(
            IAmazonEC2 client,
            INotificationService notificationService,
            ILogger<Ec2InstanceStateManager> logger)
        {
            _client = client;
            _logger = logger;
            instanceName = config.ResourceIdentifier;            
        }
 }

What I want to do is actually get multiple/IEnumerable<INotificationService> injected into the consuming service InstanceStateManager, so that I can for/each over and publish to multiple subscribers. The use case I have now would utilize two (or more) SnsNotificationService but would need to be constructed with a different value for the constructor parameter topicArn.
Note, I will have those additional values for the topicArn parameter required for constructing all instances of SnsNotificationService at registration time.

smk081
  • 783
  • 1
  • 10
  • 36
  • May https://autofac.readthedocs.io/en/latest/advanced/keyed-services.html#resolving-with-an-index helps you ? – Cyril Durand Jan 30 '23 at 09:47
  • Metadata is good choice for your case. Check it [at](https://autofac.readthedocs.io/en/latest/advanced/metadata.html#consuming-metadata) – ThomasLee Jul 27 '23 at 13:47

0 Answers0