Castle Windsor - multiple implementation of an interface

前端 未结 4 1543
小鲜肉
小鲜肉 2020-12-09 16:02

While registering components in Castle Windsor, how do we bind specific implementation of an interface to a component that has a dependency on that interface. I know in adva

4条回答
  •  春和景丽
    2020-12-09 16:38

    My answer maybe not the best one, you can use naming method to resolve multi implementation:

     container.Register(Component.For(typeof(ILogger))
              .ImplementedBy(typeof(FileLogger))
              .Named("FileLoggerIoC")
              .LifestylePerWebRequest() ,
              Component.For(typeof(ILogger))
              .ImplementedBy(typeof(DatabaseLogger))
              .Named("DatabaseLoggerIoC")
              .LifestylePerWebRequest());
    

    In your calling functions, you need to resolve it by name :-

    var fileLog = container.Resolve("FileLoggerIoC", typeof(ILogger));
    var DbLog = container.Resolve("DatabaseLoggerIoC", typeof(ILogger));
    

    Mine method maybe not the best one as people don't like service locator to get the components, you can use this as temporary solution.

提交回复
热议问题