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

边栏推荐
- [C language] the difference between structure pointer and structure variable as formal parameters
- GO语言-栈的应用-表达式求值
- Leetcode notes 566. Reshaping the matrix
- R language uses LM function to build multiple linear regression model, writes regression equation according to model coefficient, and uses conflict function to give 95% confidence interval of regressi
- Continuous (integration -- & gt; delivery -- & gt; deployment)
- 朋友发来几个面试题
- How to check if the interface cannot be adjusted? I didn't expect that the old bird of the 10-year test was planted on this interview question
- Remember to use pdfbox once to parse PDF and obtain the key data of PDF
- 数据库系统原理与应用教程(060)—— MySQL 练习题:操作题 11-20(四)
- 30天刷题计划(三)
猜你喜欢

After finishing, help autumn move, I wish you call it an offer harvester

30天刷题计划(二)

火山石投资章苏阳:硬科技,下一个10年相对确定的答案

DDoS protection with iptables

屈辱、抗争、逆转,三十年,中国该赢微软一次了

Half wave rectification light LED

严格模式——let和const——箭头函数——解构赋值——字符串模板symbol——Set和Map——生成器函数

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

Continuous (integration -- & gt; delivery -- & gt; deployment)

I'm bald! Who should I choose for unique index or general index?
随机推荐
屈辱、抗争、逆转,三十年,中国该赢微软一次了
性能超群!牛津&上海AI Lab&港大&商汤&清华强强联手,提出用于引用图像分割的语言感知视觉Transformer!代码已开源...
SQL每日一练(牛客新题库)——第4天:高级操作符
Leetcode notes 118. Yang Hui triangle
使用 Fail2ban 保护 Web 服务器免受 DDoS 攻击
UVA1599理想路径题解
C language: merge sort
I miss the year of "losing" Li Ziqi
记一次使用pdfbox解析pdf,获取pdf的关键数据的工具使用
火山石投资章苏阳:硬科技,下一个10年相对确定的答案
SQL daily practice (Niuke new question bank) - day 4: advanced operators
Jar package
What is the reason why the words behind word disappear when typing? How to solve it?
【架构】评分较高的三本微服务书籍的阅读笔记
I'm bald! Who should I choose for unique index or general index?
Tutorial on the principle and application of database system (058) -- MySQL exercise (2): single choice question
GO语言-栈的应用-表达式求值
R language test sample proportion: use prop The test function performs the single sample proportion test to calculate the confidence interval of the p value of the successful sample proportion in the
PHP generates random numbers (nickname random generator)
长封闭期私募产品再现 业内人士看法各异