温莎城堡:按公约注册,注册部分

时间:2017-09-04 12:14:13

标签: c# dependency-injection castle-windsor

我正在使用Castle Windsor作为我的DI容器。我注册了我的服务,指定了一个名称:

container.Register(Component.For<MyService>().Named("MyService"));

问题是我的系统中有很多服务而且我已经厌倦了注册其中的每一个。如何按惯例执行此操作而不会丢失Named部分? (我不介意用与该类相同的名称调用我的服务)

1 个答案:

答案 0 :(得分:6)

您可以使用以下命令注册从某个基础/接口派生的所有服务,然后配置其名称:

WindsorContainer container = new WindsorContainer();
container.Register(Classes.FromThisAssembly()
                          .BasedOn<IService>()
                          .Configure(c => c.Named(c.Implementation.Name)));

对于以下示例:

public interface IService { }
public class Service1 : IService { }
public class Service2 : IService { }
public class Service3 : IService { }
public class Service4 : IService { }
public class Service5 : IService { }
public class Service6 : IService { }

输出是:

enter image description here

还有其他方法可以选择要注册的类。查看更多in documentation