当前位置:网站首页>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

边栏推荐
- 产品经理:岗位职责表
- Operator3-设计一个operator
- 国产API管理工具Eolink太好用了,打造高效的研发利器
- 从手机厂高位“出走”的三个男人
- Excellent performance! Oxford, Shanghai, AI Lab, Hong Kong University, Shangtang, and Tsinghua have joined forces to propose a language aware visual transformer for reference image segmentation! Open
- Strict mode -- let and const -- arrow function -- Deconstruction assignment -- string template symbol -- set and map -- generator function
- What if the server cannot be connected (the original server cannot find the target resource)
- SAP UI5 FileUploader 控件实现本地文件上传,接收服务器端的响应时遇到跨域访问错误的试读版
- R语言可视化散点图、使用ggrepel包的geom_text_repel函数避免数据点之间的标签互相重叠(使用参数xlim和ylim将标签添加到可视化图像的特定区域、指定标签线段并添加箭头)
- 要想组建敏捷团队,这些方法不可少
猜你喜欢

Better and more modern terminal tools than xshell!

性能超群!牛津&上海AI Lab&港大&商汤&清华强强联手,提出用于引用图像分割的语言感知视觉Transformer!代码已开源...

Denial of service DDoS Attacks

Cool operation preheating! Code to achieve small planet effect

酷炫操作预热!代码实现小星球特效

Beyond istio OSS -- current situation and future of istio Service Grid

基于神经网络的帧内预测和变换核选择

Shell basic concepts and variables

从手机厂高位“出走”的三个男人

沾上趣店,都得道歉?
随机推荐
Cesium pit -- pit used by various API calls and API itself
Humiliation, resistance, reversal, 30 years, China should win Microsoft once
LyScript 获取上一条与下一条指令
力扣 2354. 优质数对的数目
30天刷题训练(一)
Is azvudine, a domestic oral new coronal drug, safe? Expert authority interpretation
Debezium series: major changes and new features of 2.0.0.beta1
After finishing, help autumn move, I wish you call it an offer harvester
jar包
Leetcdoe-342. Power of 4
GO语言-栈的应用-表达式求值
Paddleclas classification practice record
R语言ggplot2可视化:使用ggpubr包的ggviolin函数可视化小提琴图、设置palette参数自定义不同水平小提琴图的边框颜色
接口调不通,如何去排查?没想到10年测试老鸟栽在这道面试题上
Continuous (integration -- & gt; delivery -- & gt; deployment)
POJ1860货币兑换题解
《如何打一场数据挖掘赛事》入门版
How to play a data mining game entry Edition
SQL daily practice (Niuke new question bank) - day 4: advanced operators
不用Swagger,那我用啥?