简体   繁体   English

asp.net 5自定义类中的依赖注入,正确的方法是什么?

[英]Dependency Injection in asp.net 5 custom classes, what is the correct way?

Trying to understand DI. 试着理解DI。

What is correct way to use services/dependency objects in custom classes? 在自定义类中使用服务/依赖项对象的正确方法是什么?

Do i need to create each class as service and add to dependency objects? 我是否需要将每个类创建为服务并添加到依赖项对象?

Or should I be using [FromServices] (previously, [Active] before beta4 ) attribute. 或者我应该使用[FromServices](以前,在beta4之前的[Active])属性。

or is there is a service object I should be passing to access them? 或者是否应该传递一个服务对象来访问它们?

What trying to understand, is how i properly code my own classes to use the DI like the controllers etc. 试图理解的是,我如何正确编写自己的类来使用DI,如控制器等。

[FromServices] is just an MVC concept. [FromServices]只是一个MVC概念。 It is not available to other parts of the ASP.NET 5 stack. 它不适用于ASP.NET 5堆栈的其他部分。

If you want to pass dependencies down the chain you have a few options: 如果你想在链中传递依赖关系,你有几个选择:

  1. Pass the service provider. 通过服务提供商。 This is quite an anti-pattern because your objects need to depend on the DI container and you are not really inverting the control. 这是一个非常反模式,因为你的对象需要依赖于DI容器而你并没有真正反转控件。
  2. Pass interfaces in constructors. 在构造函数中传递接口。 The "pure" DI but you might end up with a parameter nightmare (objects that take 10 arguments in constructor). “纯粹的”DI,但你最终可能会遇到一个参数噩梦(在构造函数中占用10个参数的对象)。
  3. Similar to the previous one but group dependencies in factories. 与前一个类似,但工厂中的组依赖性。 More DI aligned and less parameter nightmare but it can create a factory nightmare. 更多的DI对齐和更少的参数噩梦,但它可以造成工厂的噩梦。
  4. Inject only top large level objects (for example: repositories, entire systems, etc). 仅注入顶级大型对象(例如:存储库,整个系统等)。 This approach is a nice tradeoff between dependency nightmare and too much coupling. 这种方法是依赖性梦魇和过多耦合之间的一个很好的权衡。 Of course, the systems that get injected should be independent from each other. 当然,注入的系统应该彼此独立。 Also, each system could have its own DI container inside. 此外,每个系统内部都可以有自己的DI容器。

!! Don't confuse DI with Configuration. 不要将DI与配置混淆。 DI makes sense when you have a dependency on a contract. 当你依赖合同时,DI是有意义的。 Configuration useful when you need some information that is specific to the current implementation. 当您需要某些特定于当前实现的信息时,配置很有用。

Example: if you have an IRepository then you shouldn't inject the connection string because connection strings are specific to a system that you connect to. 示例:如果您有IRepository则不应注入连接字符串,因为连接字符串特定于您连接的系统。 There are cases when connection strings don't make sense. 有些情况下连接字符串没有意义。 For example, an InMemoryRepository will not require a connection string and thus that is not a common dependency for all implementations. 例如, InMemoryRepository不需要连接字符串,因此这不是所有实现的常见依赖项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM