Autofac with multiple implementations of the same interface

前端 未结 4 1887
小鲜肉
小鲜肉 2021-02-03 21:17

I\'m using Autofac and would like to have multiple implementations of an interface. How can I configure Autofac so to resolve dependencies based on the current type?

Mor

4条回答
  •  滥情空心
    2021-02-03 21:34

    For anyone else searching, I just ran across this. You can use implicit support for the IEnumerable. I wrote it up for future use.

    Basically, you can register assembly types by name (or other criteria) as an IEnumerable which can be consumed later. My favorite part of this approach is that you can keep adding message handlers and as long as you stick to the same criteria, you never have to touch the criteria afterwards.

    Autofac Registration:

    builder.RegisterAssemblyTypes(typeof (LoggingMessageHandler).Assembly)
      .Where(x => x.Name.EndsWith("MessageHandler"))
      .AsImplementedInterfaces();
    

    Consuming Class:

    public class Foo
    {
      private readonly IEnumerable _messageHandlers
    
      public Foo(IEnumerable messageHandlers)
      {
        _messageHandlers = messageHandlers;
      }
    
      public void Bar(message)
      {
        foreach(var handler in _messageHandlers)
        {
          handler.Handle(message)
        }
      }
    }
    

提交回复
热议问题