Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Castle Windsor: Register by Convention with Named part

I'm using Castle Windsor as my DI container. I registered my service specifying a name:

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

The problem is that I have a lot of services in my system and I'm tired of register each one of them. how can I do this by convention without loosing the Named part? (I don't mind calling my services with the same name as the class)

like image 445
Eitan Avatar asked Dec 07 '25 08:12

Eitan


1 Answers

You can use the following to register all services deriving from some base/interface and then configure their name:

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

For the following example:

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 { }

Output was:

enter image description here


There are additional ways for selecting which classes to register. See more in documentation

like image 167
Gilad Green Avatar answered Dec 09 '25 22:12

Gilad Green



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!