我想将简单的注入器集成到我们的应用程序中,我需要找到一种方法来实现一个IsRegistered方法来查看是否在容器中注册了一个类型。我怎样才能实现这个?SimpleInjector IsRegistered方法?
2
A
回答
1
类似IsRegistered
的方法在Simple Injector中没有实现,因为你不需要它。这种方法会导致Service Locator anti-pattern,应该不惜一切代价避免。
不必查询某个类型的存在,即使没有任何东西需要实现,也要确保始终注册一个实现。注册一个空实现(执行Null Object Pattern,不要与null reference混淆)。注入一个Null对象使消耗代码更容易,并且使测试变得更容易,因为依赖关系只是必需的,您将失去空检查并调用IsRegistered
。
但是在某些情况下,您可能会在您的Composition Root(取决于并调用容器的位置)进行某些检查。即使在这些情况下,使用IsRegistered
将是非常罕见的(我从来没有看到它的实际用途),尽管有cases查询容器的注册是非常有用的。
public static bool IsRegistered(this Container container, Type serviceType)
{
return container.GetRegistration(serviceType) != null;
}
:
尽管如此,该方法可以很容易地通过请求一个登记实现
相关问题
- 1. isRegistered()与isRegisteredOnServer()
- 2. isRegistered not returns true
- 3. GreenRobot:EventBus的isRegistered()方法不按预期方式工作
- 4. 统一DI。泛型类型注册和IsRegistered方法
- 5. SimpleInjector和FluentValidationFactory
- 6. SimpleInjector RegisterWebApiRequest vs RegisterPerWebRequest
- 7. SimpleInjector RegisterAll for Web Api
- 8. SimpleInjector RegisterAll懒惰地
- 9. 对SimpleInjector的Container.GetInstance()方法的性能影响
- 10. 如何使用SimpleInjector在嵌套方法中获取DbContext
- 11. SimpleInjector意外行为
- 12. SimpleInjector和System.Web.Mvc.Async线程
- 13. ASP.NET MVC 5 + Owin + SimpleInjector
- 14. CellInfo api isRegistered()总是返回false
- 15. 使用SimpleInjector消耗WCF
- 16. 使用SimpleInjector获取HubContext
- 17. 使用的WebAPI,SimpleInjector和MediatR
- 18. 使用simpleinjector注册opengeneric
- 19. SimpleInjector惰性通用注册
- 20. SimpleInjector和自定义WebViewPage
- 21. SimpleInjector和Microsoft Webhook ASP.Net Webhooks
- 22. SimpleInjector命名参数注册
- 23. SimpleInjector - 装饰者不开火?
- 24. 使用SimpleInjector注入ISession时的生活方式不匹配
- 25. 如何正确使用SimpleInjector - RegisterAllOpenGeneric
- 26. MediatR和SimpleInjector的依赖范围问题
- 27. SimpleInjector结合WCF和“正规”注册
- 28. SimpleInjector不工作 - 在OWIN的Web API
- 29. 依赖注入(使用SimpleInjector)和OAuthAuthorizationServerProvider
- 30. RegisterOpenGeneric与SimpleInjector解析不正确类型