Search code examples
c#serviceautofac

autofac multiple services (same interface - multiple addons providing it) how to implement?


I have a service interface, lets say IAddonServiceX which is implemented by many, but not all addons to a system. I want to have an IEnumerable so that I could iterate and execute methods for every addon that registered this service? Ho can this be done with autofac?


Solution

  • Autofac has implicit support for it, so you just need register your implementations with

    builder.RegisterType<Impl1>.As<IAddonServiceX>();    
    builder.RegisterType<Impl2>.As<IAddonServiceX>();
    

    And when you are resolving an IEnumerable<IAddonServiceX> with container.Resolve<IEnumerable<IAddonServiceX>> or using IEnumerable<IAddonServiceX> in your constructor then Autofac will provide you all the implementations.