Blame view

泰额版/Food Labeling Management Code/Yi.Doc.Md/02.框架功能模块教程/03.依赖注入.md 979 Bytes
59e51671   “wangming”   1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  ## 简介
  熟悉Asp.NetCore的小伙伴们,对依赖注入可太熟悉,这里也不在过多的讲述依赖注入知识
  默认内置的注入方式,通常是在启动类文件,一个一个手动注入,例如:
  ``` cs
  service.Addsingle<接口,类>()
  ```
  同样,当服务过多,添加服务的代码会显的非常长,不够优雅
  可以使用框架内置的接口
  - IScopedDependency
  - ISingletonDependency
  - ITransientDependency
  
  也可以使用框架内置的特性
  - DependencyAttribute
  - ExposeServicesAttribute
  
  > 使用特性,可以指定特定类、接口作为抽象
  ## 如何使用
  #### 特性方式:
  在实现类上标注特性即可
  ``` cs
  [ExposeServices(typeof(ITestService))]
  [Dependency(ServiceLifetime.Transient)]
  public class Test
  {
  }
  ```
  
  #### 接口方式:
  同理,根据不同的接口,选择不同的生命周期,自动会优先找自动以`I+类名`的接口作为抽象
  ``` cs
  public class Test:ITest,ISingletonDependency
  {
  }
  ```