这些注册有什么区别?
public void ConfigureServices(IServiceCollection services) { services.AddTransient< IService,Service>(); services.AddScoped< IService,Service>(); services.AddSingleton< IService,Service>(); services.AddInstance(service); }
解决方案
对于遵循SOLID原则的任何相当大尺寸应用程序的产品开发,vNext的内置DI容器将无用,因为:
- 它不能帮助您验证配置,使得很难诊断来自常见配置错误的问题,例如俘虏依赖关系。在相当大的应用程序中,实际上很难自己发现这些错误。
- 使用拦截器或装饰器。这使得维护任何合理大小的应用程序真的很贵。
- 尽管它支持将打开的通用抽象映射到打开的通用实现,但它无法使用类型约束的泛型类型。
内置容器还有其他限制,例如只能使用单个构造函数支持类型,但这是非常合理的默认值,因为您的注射器应该只有一个构造函数。自从rc1以来,现在有了一种多功能的支持。
如果你从一个新的和简单的项目开始,我的建议是应用纯DI (这意味着手机组件没有使用容器)并通过插入您的自定义IControllerActivator 。之后,当批处理注册和装饰等功能将提高组成根目录的维护性,切换到符合您要求的已建立的DI库之一。
As currently there is lack of documentation on DI topic - Dependency Injection. Can someone help me to understand following:
What is the difference between these registrations?
public void ConfigureServices(IServiceCollection services) { services.AddTransient<IService, Service>(); services.AddScoped<IService, Service>(); services.AddSingleton<IService, Service>(); services.AddInstance(service); }解决方案
For product development of any considerably sized application that follows the SOLID principles, vNext's built-in DI container will be useless, because:
- It doesn't help you in verifying your configuration, making it really hard to diagnose problems that come from common misconfigurations, such as Captive Dependencies. In a reasonably sized application, it's actually quite hard to spot these mistakes yourself.
- It is impossible to apply cross-cutting concerns using interceptors or decorators. This makes maintaining any reasonably sized application really expensive.
- Although it supports mapping of open generic abstractions to open generic implementations, it is unable to work with generic types with type constraints.
There are other limitations to the built-in container, such as only being able to support types with a single constructor, but this is a very reasonable default, because your injectables should only have a single constructor anyway. since rc1, there is now some kind of multi-ctor support.
If you start with a new and simple project, my advice is to apply Pure DI (which means hand-wired components without the use of a container) and resolve your types by plugging in your custom IControllerActivator. Later on, when features such as batch-registration and decoration would improve maintainability of your composition root, switch to one of the established DI libraries that fits your requirements.
更多推荐
ASP.NET Core中的依赖注入(vNext)
发布评论