我的服务接口的命名空间为Services.Interfaces
服务接口的实现有一个命名空间Web.UI.Services
例如,我有 2 个服务实现
- IUserService 需要注册到UserService
- ICountryService 需要注册到CountryService
这就是我目前使用 SimpleInjector 注册这些服务的方式。
container.Register<IUserService, UserService> ();
container.Register<ICountryService, CountryService> ();
问题:如果我有超过 100 个服务,那就有点夸张了。我需要为每项服务添加一行。
如何使用简单注入器将一个程序集的所有实现注册到另一程序集的所有接口?
您可以通过使用 LINQ 和反射查询程序集并注册所有类型来完成此操作:
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);
}
这是描述的here http://simpleinjector.readthedocs.io/en/latest/advanced.html#batch-registration.
如果我有超过 100 个服务就有点夸张了。我需要去添加
每项服务都有一行。
如果是这样的话,我会认为你的设计有问题。您致电您的服务这一事实IUserService
and ICountryService
表明您违反了单一职责 https://en.wikipedia.org/wiki/Single_responsibility_principle, 打开关闭 https://en.wikipedia.org/wiki/Open/closed_principle and 接口隔离原则 https://en.wikipedia.org/wiki/Interface_segregation_principle。这可能会导致严重的可维护性问题。
对于替代设计,请查看these https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91 two https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92文章。所描述的设计允许更高级别的可维护性,使注册服务变得更加容易,并使应用横切关注点变得轻而易举(尤其是使用简单注入器)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)