Files
Yi.Framework/Yi.Doc.Md/02.框架功能模块教程/03.依赖注入.md
2023-12-23 21:14:56 +08:00

35 lines
979 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
## 简介
熟悉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
{
}
```