简单的喷油器注册的所有服务从命名空间 [英] Simple Injector Register All Services From Namespace

查看:90
本文介绍了简单的喷油器注册的所有服务从命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务接口有 Services.Interfaces

服务接口的实现具有 Web.UI.Services

我有例如2服务实现


  • IUserService,需要注册到UserService

  • ICountryService,需要注册才能CountryService

这是我目前与SimpleInjector注册这些服务。

This is how I currently register these services with SimpleInjector.

container.Register<IUserService, UserService> ();
container.Register<ICountryService, CountryService> ();

问题:如果我有100多个服务夸张了一点。我需要去添加一行为每个服务。

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?

推荐答案

您可以通过查询过与LINQ和反思大会做到这一点,注册所有类型的:

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);
}

这是描述这里

如果我有超过100个服务夸张了一点。我需要去添加
  每个服务一个行

If I have over 100 services to exaggerate a bit. I need to go and add a line for each service.

如果是这样的话,我会认为有什么不对您的设计。你打电话给你的服务 IUserService ICountryService 的事实是,你违反的单一责任,的打开/关闭接口隔离原则。这可能会导致严重的可维护性的问题。

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.

有关的替代设计,看看在这些 2 文章。所描述的设计使得可维护性更高水平,使得它更容易注册您的服务,使应用横切关注孩子的发挥(尤其是简单的喷油器)。

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).

这篇关于简单的喷油器注册的所有服务从命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆