My Service Interfaces has a namespace of Services.Interfaces
The implementation of the Service Interfaces has a namespace of Web.UI.Services
I have 2 service implementations for example
This is how I currently register these services with SimpleInjector.
container.Register<IUserService, UserService> ();
container.Register<ICountryService, CountryService> ();
Problem: If I have over 100 services to exaggerate a bit. I need to go and add a line for each service.
How can I register all the implementations from one assembly to all the interfaces form another assembly using Simple Injector?
You can do this by querying over the assembly with LINQ and reflection and register all the types:
var registrations =
from type in typeof(UserService).Assembly.GetExportedTypes()
where type.Namespace.StartsWith("Services.Interfaces")
where type.GetInterfaces().Any()
select new { Service = type.GetInterfaces().Single(), Implementation = type };
foreach (var reg in registrations) {
container.Register(reg.Service, reg.Implementation);
}
This is described here.
If I have over 100 services to exaggerate a bit. I need to go and add a line for each service.
If this is the case, I would argue that there is something wrong with your design. The fact that you call your services IUserService
and ICountryService
is an indication that you are violating the Single Responsibility, Open/closed and Interface Segregation Principles. This can cause serious maintainability issues.
For an alternative design, take a look at the these two articles. The described design allows a much higher level of maintainability, makes it much easier to register your services, and makes applying cross-cutting concerns childs play (especially with Simple Injector).