当前位置:网站首页>7. Dependency injection
7. Dependency injection
2022-07-28 13:47:00 【Masa technical team】
Register as agreed
Masa It introduces service registration according to the contract , According to the Convention, it is greater than the configuration , Developers don't have to do anything , The framework will automatically complete the registration
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 )
Example :
``` C#public class StorageOptions : ITransientDependency{ }```characteristic
IgnoreInjection
Ignore injection , Used to exclude not being automatically injected
- 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)
Example :
``` C#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++; }}```The effect is equivalent to :services.AddSingleton<
BaseService>(); services.AddSingleton<GoodsService>();
Dependency
coordination ISingletonDependency、IScopedDependency、ITransientDependency Use , The implementation service is registered only once
- TryRegister: Set up true Then the service will only be registered if it is not registered , similar IServiceCollection Of TryAdd ... Extension method .
Example :
``` C#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; }}```The effect is equivalent to :services.AddSingleton<
ICache,MemoryCache>();
- ReplaceServices: Set up true Then replace the previously registered service , similar IServiceCollection Of Replace ... Extension method .
Example :
``` C#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";}```The effect is equivalent to :services.AddSingleton<
IEncryptionService,Sha1EncryptionService>();
Quick start
- install .Net 6.0
New unit test project
Assignment.DependencyInjection, choiceMSTest, And installMasa.Utils.Extensions.DependencyInjectiondotnet new xunit -o Assignment.DependencyInjectioncd Assignment.DependencyInjectiondotnet add package Masa.Utils.Extensions.DependencyInjection --version 0.5.0-preview.2The new class
StorageOptionspublic 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
If you need to use the automatic registration service according to the contract , Please remember
- 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)]
- If you want to provide by default
Source code of this chapter
Assignment07
https://github.com/zhenlei520/MasaFramework.Practice
Open source address
MASA.BuildingBlocks:https://github.com/masastack/MASA.BuildingBlocks
MASA.Contrib:https://github.com/masastack/MASA.Contrib
MASA.Utils:https://github.com/masastack/MASA.Utils
MASA.EShop:https://github.com/masalabs/MASA.EShop
MASA.Blazor:https://github.com/BlazorComponent/MASA.Blazor
If you treat our MASA Framework Interested in , Whether it's code contribution 、 Use 、 carry Issue, Welcome to contact us

边栏推荐
- 国产API管理工具Eolink太好用了,打造高效的研发利器
- Kotlin learning notes 3 - lambda programming
- 力扣 2354. 优质数对的数目
- After finishing, help autumn move, I wish you call it an offer harvester
- DOJNOIP201708奶酪题解
- Deployment之滚动更新策略。
- 酷炫操作预热!代码实现小星球特效
- 比XShell更好用、更现代的终端工具!
- 7.依赖注入
- R语言使用lm函数构建线性回归模型、使用subset函数指定对于数据集的子集构建回归模型(使用floor函数和length函数选择数据前部分构建回归模型)
猜你喜欢

倒计时 2 天!2022 中国算力大会:移动云邀您共见算力网络,创新发展

SQL每日一练(牛客新题库)——第4天:高级操作符

Use non recursive method to realize layer traversal, preorder traversal, middle order traversal and post order traversal in binary tree

Shell basic concepts and variables

7.依赖注入

You have to apologize if you get involved in the funny shop?

jar包

30天刷题训练(一)

word打字时后面的字会消失是什么原因?如何解决?

拒绝服务 DDoS 攻击
随机推荐
R语言ggplot2可视化:使用ggpubr包的ggviolin函数可视化小提琴图、设置draw_quantiles参数添加指定分位数横线(例如,50%分位数、中位数)
C语言:随机生成数+快速排序
Is azvudine, a domestic oral new coronal drug, safe? Expert authority interpretation
R语言ggplot2可视化:可视化散点图并为散点图中的数据点添加文本标签、使用ggrepel包的geom_text_repel函数避免数据点标签互相重叠(自定义指定字体类型font family)
PHP generates random numbers (nickname random generator)
【C语言】结构体指针与结构体变量作形参的区别
C language: random number + quick sort
jar包
Go language - Application of stack - expression evaluation
数据库系统原理与应用教程(058)—— MySQL 练习题(二):单选题
酷炫操作预热!代码实现小星球特效
[dark horse morning post] byte valuation has shrunk to $270billion; "Second uncle" video author responded to plagiarism; Renzeping said that the abolition of the pre-sale system of commercial housing
30天刷题计划(三)
You have to apologize if you get involved in the funny shop?
Better and more modern terminal tools than xshell!
R语言ggplot2可视化:使用ggpubr包的ggviolin函数可视化小提琴图、设置palette参数自定义不同水平小提琴图的边框颜色
Leetcode notes 566. Reshaping the matrix
倒计时 2 天!2022 中国算力大会:移动云邀您共见算力网络,创新发展
图的遍历(BFS&&DFS基础)
Facial expression recognition based on pytorch convolution - graduation project "suggestions collection"