当前位置:网站首页>7. Dependency injection
7. Dependency injection
2022-07-25 18:20:00 【MASA 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.DependencyInjection cd Assignment.DependencyInjection dotnet 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

边栏推荐
猜你喜欢

The new version of 3dcat v2.1.3 has been released. You can't miss these three function updates!

ORB_SLAM3复现——上篇

Design practice of Netease strictly selecting inventory center

想要做好软件测试,可以先了解AST、SCA和渗透测试

Cloud VR: the next step of virtual reality specialization

Boomi won the "best CEO in diversity" and the "best company in career growth" and ranked among the top 50 in the large company category

Related operations of figure

Construction of Huffman tree

用GaussDB(for Redis)存画像,推荐业务轻松降本60%

Use of LCD screen of kendryte k210 on FreeRTOS
随机推荐
Keil5 "loading PDSC debug description failed for STMicroelectronics stm32hxxxxxxx" solution
Use of C language cjson Library
Why is the index in [mysql] database implemented by b+ tree? Is hash table / red black tree /b tree feasible?
ORB_SLAM3复现——上篇
MATLAB中join函数使用
Tkinter GUI address book management system
Why the future of digitalization depends on 3D real-time rendering
一次备库的坏块的修复过程
Today's sleep quality record is 84 points
Landmark buildings around the world
更新|3DCAT实时云渲染 v2.1.2版本全新发布
MySQL optimistic lock
vim基本操作命令
二叉树的相关操作
Number two 2010 real test site
Unittest framework application
Remember those two sentences
CVE-2022-33891 Apache spark shell 命令注入漏洞复现
c语言---25 扫雷游戏
推荐一个沁恒的蓝牙的参考博客