当前位置:网站首页>7.依赖注入
7.依赖注入
2022-07-25 16:32:00 【InfoQ】
按照约定的注册
依赖接口
- ISingletonDependency: 注册生命周期为Singleton的服务
- IScopedDependency: 注册生命周期为Scoped的服务
- ITransientDependency: 注册生命周期为Transient的服务
- IAutoFireDependency: 自动触发(与ISingletonDependency、IScopedDependency、ITransientDependency结合使用,在服务自动注册结束后触发一次获取服务操作,仅继承IAutoFireDependency不起作用)
public class StorageOptions : ITransientDependency
{
}
特性
IgnoreInjection
- Cascade: 设置为true时,当前类以及子类都不再被自动注册,设置为false,仅当前类不被自动注册(默认false)
public class BaseService : ISingletonDependency
{
public static int Count { get; set; } = 0;
public BaseService()
{
Count++;
}
public BaseService(bool isChildren)
{
}
}
[IgnoreInjection]
public class GoodsBaseService : BaseService
{
public GoodsBaseService() : base(true)
{
}
}
public class GoodsService : GoodsBaseService
{
public static int GoodsCount { get; set; } = 0;
public GoodsService()
{
GoodsCount++;
}
}
BaseServiceGoodsServiceDependency
- TryRegister: 设置true则仅当服务未注册时才会被注册,类似IServiceCollection的TryAdd ... 扩展方法.
public interface ICache : ISingletonDependency
{
void Set(string key, string value);
}
[Dependency(TryRegister = true)]
public class EmptyCache : ICache
{
public void Set(string key, string value)
{
throw new NotSupportedException($"暂不支持{nameof(Set)}方法");
}
}
public class MemoryCache : ICache
{
private readonly ConcurrentDictionary<string, Lazy<string>> _dicCache = new();
public void Set(string key, string value)
{
_ = _dicCache.AddOrUpdate
(
key,
k => new Lazy<string>(() => value, LazyThreadSafetyMode.ExecutionAndPublication),
(_, _) => new Lazy<string>(() => value, LazyThreadSafetyMode.ExecutionAndPublication)
).Value;
}
}
ICacheMemoryCache- ReplaceServices: 设置true则替换之前已经注册过的服务,类似IServiceCollection的Replace ... 扩展方法.
public interface IEncryptionService : ISingletonDependency
{
string MethodName { get; }
}
[Dependency(ReplaceServices = true)]
public class Sha1EncryptionService : IEncryptionService
{
public string MethodName => "Sha1";
}
public class Md5EncryptionService : IEncryptionService
{
public string MethodName => "Md5";
}
IEncryptionServiceSha1EncryptionService快速入门
- 安装.Net 6.0
- 新建单元测试项目
Assignment.DependencyInjection,选择MSTest,并安装Masa.Utils.Extensions.DependencyInjection
dotnet new xunit -o Assignment.DependencyInjection
cd Assignment.DependencyInjection
dotnet add package Masa.Utils.Extensions.DependencyInjection --version 0.5.0-preview.2
- 新建类
StorageOptions
public class StorageOptions : ITransientDependency
{
}
- 新建类
DITest
[TestClass]
public class DITest
{
private IServiceCollection _services;
[TestInitialize]
public void Init()
{
_services = new ServiceCollection();
_services.AddAutoInject();//执行自动注入
}
[TestMethod]
public void TestAutoInject()
{
Assert.IsTrue(_services.Any<StorageOptions>(ServiceLifetime.Transient));//判断StorageOptions注册成功,且生命周期为Transient
}
private IServiceProvider ServiceProvider => _services.BuildServiceProvider();
}
总结
- 根据业务需要,则指定类或接口中实现以下接口
ISingletonDependency单例(项目启动后仅初始化一次)
IScopedDependency请求 (每次请求仅初始化一次)
ITransientDependency瞬时(每次获取都会被初始化)
- 抽象类不会被自动注册
- 如果你有一个自定义接口
IRepository,且希望接口以及对应的默认实现类RepositoryBase会被自动注册生命周期为Scoped,则接口IRepository应该继承IScopedDependency
- 如果你希望默认提供的
RepositoryBase可以被用户定义的类替换,则应该在RepositoryBase上方增加[Dependency(TryRegister = true)],那用户仅需要实现IRepository即可
- 或不更改默认提供的
RepositoryBase,用户实现IRepository后,并在新的实现类上方增加[Dependency(ReplaceServices = true)]
本章源码
开源地址

边栏推荐
- C# 模拟抽奖
- 01. A simpler way to deliver a large number of props
- Who moved my memory and revealed the secret of 90% reduction in oom crash
- 柏睿数据加入阿里云PolarDB开源数据库社区
- 如何构建面向海量数据、高实时要求的企业级OLAP数据引擎?
- Cookie、cookie与session区别
- 在 NgModule 里通过依赖注入的方式注册服务实例
- Exclusive lock
- EMQX Cloud 更新:日志分析增加更多参数,监控运维更省心
- LVGL 7.11 tileview界面循环切换
猜你喜欢

柏睿数据加入阿里云PolarDB开源数据库社区

Talk about how to use redis to realize distributed locks?

解决Win10磁盘占用100%

Test Driven Development (TDD) online practice room | classes open on September 17
![[wechat applet] detailed explanation of applet host environment](/img/57/582c07f6e6443f9f139fb1af225ea4.png)
[wechat applet] detailed explanation of applet host environment

3D 语义分割——Scribble-Supervised LiDAR Semantic Segmentation

fastadmin tp 安装使用百度富文本编辑器UEditor

QT ListView 列表显示组件笔记

EMQX Cloud 更新:日志分析增加更多参数,监控运维更省心
![[fault diagnosis] bearing fault diagnosis based on Bayesian optimization support vector machine with matlab code](/img/9e/138e4b160fa9bd6486fac44a788d09.png)
[fault diagnosis] bearing fault diagnosis based on Bayesian optimization support vector machine with matlab code
随机推荐
MySQL isolation level transactions
Baidu rich text editor ueeditor single image upload cross domain
用递归进行数组求和
如何构建面向海量数据、高实时要求的企业级OLAP数据引擎?
Attachment handling of SAP Fiori
终极套娃 2.0 | 云原生交付的封装
百度富文本编辑器UEditor单张图片上传跨域
How to build an enterprise level OLAP data engine for massive data and high real-time requirements?
可验证随机函数 VRF
【obs】发送前丢帧及帧优先级
Exploration of 6-wire SPI transmission mode
MQTT X CLI 正式发布:强大易用的 MQTT 5.0 命令行工具
【图像隐藏】基于混合 DWT-HD-SVD 的数字图像水印方法技术附matlab代码
[xiao5 chat] check the official account < the service provided by the official account has failed, please wait a moment>
Visual studio 2022 view class diagram
【obs】转载:OBS直播严重延迟和卡顿怎么办?
Two methods of importing sqllite table from MySQL
Gap locks
测试框架-unittest-测试套件、结果输出到文件
Intention lock