[英]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: 如果你想在链中传递依赖关系,你有几个选择:
!! ! 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.