当前位置:网站首页>7. Dependency injection
7. Dependency injection
2022-07-25 16:32:00 【InfoQ】
Register as agreed
Dependent interface
- ISingletonDependency: The registration life cycle is Singleton Service for
- IScopedDependency: The registration life cycle is Scoped Service for
- ITransientDependency: The registration life cycle is Transient Service for
- IAutoFireDependency: Automatic triggering ( And ISingletonDependency、IScopedDependency、ITransientDependency Use a combination of , After the automatic registration of the service is completed, a get service operation is triggered , Just inherit IAutoFireDependency It doesn't work )
public class StorageOptions : ITransientDependency
{
}
characteristic
IgnoreInjection
- Cascade: Set to true when , The current class and subclasses are no longer automatically registered , Set to false, Only the current class is not automatically registered ( Default 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: Set up true Then the service will only be registered if it is not registered , similar IServiceCollection Of TryAdd ... Extension method .
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($" Temporary does not support {nameof(Set)} Method ");
}
}
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: Set up true Then replace the previously registered service , similar IServiceCollection Of Replace ... Extension method .
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";
}
IEncryptionServiceSha1EncryptionServiceQuick start
- install.Net 6.0
- New unit test project
Assignment.DependencyInjection, choiceMSTest, And installMasa.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
- The new class
StorageOptions
public class StorageOptions : ITransientDependency
{
}
- The new class
DITest
[TestClass]
public class DITest
{
private IServiceCollection _services;
[TestInitialize]
public void Init()
{
_services = new ServiceCollection();
_services.AddAutoInject();// Perform automatic injection
}
[TestMethod]
public void TestAutoInject()
{
Assert.IsTrue(_services.Any<StorageOptions>(ServiceLifetime.Transient));// Judge StorageOptions Registered successfully , And the life cycle is Transient
}
private IServiceProvider ServiceProvider => _services.BuildServiceProvider();
}
summary
- According to business needs , Then the following interfaces are implemented in the specified class or interface
ISingletonDependencySingle case ( Only initialize once after the project is started )
IScopedDependencyrequest ( Initialize only once per request )
ITransientDependencyinstantaneous ( Each acquisition is initialized )
- Abstract classes are not automatically registered
- If you have a custom interface
IRepository, And you want the interface and the corresponding default implementation classRepositoryBaseWill be automatically registered with a lifecycle of Scoped, InterfaceIRepositoryShould inheritIScopedDependency
- If you want to provide by default
RepositoryBaseCan be replaced by user-defined classes , Should be inRepositoryBaseIncrease above [Dependency(TryRegister = true)], The user only needs to realizeIRepositorythat will do
- Or do not change the default
RepositoryBase, User implementationIRepositoryafter , And add [Dependency(ReplaceServices = true)]
Source code of this chapter
Open source address

边栏推荐
- Talk about how to use redis to realize distributed locks?
- Register service instances in ngmodule through dependency injection
- [xiao5 chat] check the official account < the service provided by the official account has failed, please wait a moment>
- 百度富文本编辑器UEditor 图片宽度100%自适应,手机端
- 80篇国产数据库实操文档汇总(含TiDB、达梦、openGauss等)
- Shared lock
- LVGL 7.11 tileview界面循环切换
- Cookie、cookie与session区别
- 2W word detailed data Lake: concept, characteristics, architecture and cases
- Win11动态磁贴没了?Win11中恢复动态磁贴的方法
猜你喜欢

MQTT X CLI 正式发布:强大易用的 MQTT 5.0 命令行工具

今天去 OPPO 面试,被问麻了

Test Driven Development (TDD) online practice room | classes open on September 17

Waterfall flow layout
![[zeloengine] summary of pit filling of reflection system](/img/7a/c85ba66c5dd05908b2d784fab306a2.png)
[zeloengine] summary of pit filling of reflection system

How does win11's own drawing software display the ruler?

微信公众号开发之消息的自动回复

一文理解分布式开发中的服务治理

谁动了我的内存,揭秘 OOM 崩溃下降 90% 的秘密
![[image hiding] digital image watermarking method technology based on hybrid dwt-hd-svd with matlab code](/img/2a/b5214e9fa206f1872293c9b9d7bdb6.png)
[image hiding] digital image watermarking method technology based on hybrid dwt-hd-svd with matlab code
随机推荐
自定义mvc项目登录注册和树形菜单
MySQL pessimistic lock
What is the shortcut key for win11 Desktop Switching? Win11 fast desktop switching method
【图像去噪】基于双立方插值和稀疏表示实现图像去噪matlab源码
Leetcode:6127. Number of high-quality number pairs [bit operation finding rules + the sum of two numbers is greater than or equal to K + dichotomy]
[zeloengine] summary of pit filling of reflection system
MQTT X CLI 正式发布:强大易用的 MQTT 5.0 命令行工具
02. Limit the parameter props to a list of types
Fudan University emba2022 graduation season - graduation does not forget the original intention and glory to embark on the journey again
伦敦银K线图的各种有用形态
[image hiding] digital image watermarking method technology based on hybrid dwt-hd-svd with matlab code
链游开发现成版 链游系统开发详细原理 链游源码交付
Emqx cloud update: more parameters are added to log analysis, which makes monitoring, operation and maintenance easier
linux内核源码分析之页表缓存
01. A simpler way to deliver a large number of props
解决Win10磁盘占用100%
MySQL之联表查询、常用函数、聚合函数
The presentation logic of mail sending and receiving inbox outbox and reply to the problem of broken chain
MySQL self incrementing lock
百度富文本编辑器UEditor单张图片上传跨域