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

边栏推荐
- 今日睡眠质量记录75分
- 二舅能治好年轻人的精神内耗吗?
- Tutorial on the principle and application of database system (059) -- MySQL exercise questions: operation questions 1-10 (III)
- 30天刷题计划(二)
- Rust 从入门到精通01-简介
- 屈辱、抗争、逆转,三十年,中国该赢微软一次了
- Rolling update strategy of deployment.
- POJ3275 Ranking the Cows题解
- 火山石投资章苏阳:硬科技,下一个10年相对确定的答案
- 力扣 2354. 优质数对的数目
猜你喜欢

111. The sap ui5 fileuploader control realizes local file upload and encounters a cross domain access error when receiving the response from the server
JWT login authentication + token automatic renewal scheme, well written!

30天刷题计划(三)

Jar package

Org.apache.ibatis.exceptions.toomanyresultsexception

接口调不通,如何去排查?没想到10年测试老鸟栽在这道面试题上

我秃了!唯一索引、普通索引我该选谁?

Intra prediction and transform kernel selection based on Neural Network

jar包

Humiliation, resistance, reversal, 30 years, China should win Microsoft once
随机推荐
力扣 剑指 Offer 51. 数组中的逆序对
今日睡眠质量记录75分
[ecmascript6] symbol and its related use
What is the reason why the words behind word disappear when typing? How to solve it?
R语言使用dpois函数生成泊松分布密度数据、使用plot函数可视化泊松分布密度数据(Poisson distribution)
SQL每日一练(牛客新题库)——第4天:高级操作符
不用Swagger,那我用啥?
.NET桌面开发的一些思考
使用 Fail2ban 保护 Web 服务器免受 DDoS 攻击
POJ3259虫洞题解
Lyscript get previous and next instructions
Volcanic stone investment Zhang Suyang: hard technology, the relatively certain answer in the next 10 years
What if the server cannot be connected (the original server cannot find the target resource)
LyScript 获取上一条与下一条指令
Holes in [apue] files
C语言:归并排序
【C语言】结构体指针与结构体变量作形参的区别
用非递归的方法实现二叉树中的层遍历,先序遍历,中序遍历和后序遍历
Is azvudine, a domestic oral new coronal drug, safe? Expert authority interpretation
数据库系统原理与应用教程(060)—— MySQL 练习题:操作题 11-20(四)