Autofac with multiple implementations of the same interface

前端 未结 4 1773
小鲜肉
小鲜肉 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:28

    Not too difficult. You can register concrete types as self and resolve it as you go along. Then your top level message handler (LoggingMessageHandler in your example) can be registered for the interface, which will be used by your TopLevelClass

    Here's what you're looking at (assuming you have a default constructor for FinalHandler)

    var builder = new ContainerBuilder();
    builder.RegisterType().AsSelf().SingleInstance();
    builder.Register(c => new DoSomethingMessageHandler(c.Resolve())).AsSelf().SingleInstance();
    builder.Register(c => new LoggingMessageHandler(c.Resolve())).As().SingleInstance();
    //now finally your top level class - this will automatically pick your LoggingMessageHandler since the others have been registered onto their concreteTypes only
    builder.RegisterType().As().InstancePerOwned();
    

提交回复
热议问题