gpt4 book ai didi

c# - 将 IOptions<> 注入(inject)静态类

转载 作者:行者123 更新时间:2023-12-05 01:17:13 30 4
gpt4 key购买 nike

我想让类保持静态。是否有任何解决方法来注入(inject) IOptions<EncryptionSettings> 不修改访问修饰符?

public static class Encrypter
{
private static readonly Encoding encoding = Encoding.UTF8;

private static readonly EncryptionSettings _encryptionSettings;

public static Encrypter(IOptions<EncryptionSettings> encryptionSettings)
{
_encryptionSettings = encryptionSettings.Value;
}

public static string Encrypt(string plainText)
{
(...)
}

public static string Decrypt(string plainText)
{
(...)
}

static byte[] HmacSHA256(String data)
{
(...)
}
}

'Encrypter.Encrypter(IOptions)': access modifiers are not allowed on static constructors

'Encrypter.Encrypter(IOptions)': a static constructor must be parameterless

最佳答案

糟糕的设计选择使该类成为静态的。

并且您正在经历与尝试将其与依赖项注入(inject)一起使用相关的挑战。静电和 DI 不能很好地混合,应尽可能避免。

将所需的功能封装在抽象之后。

public interface IEncrypter {
string Encrypt(string plainText);
string Decrypt(string plainText);
}

并实现

public class Encrypter : IEncrypter {
private static readonly Encoding encoding = Encoding.UTF8;
private readonly EncryptionSettings _encryptionSettings;

public Encrypter(IOptions<EncryptionSettings> encryptionSettings) {
_encryptionSettings = encryptionSettings.Value;
}

public string Encrypt(string plainText) {
//(...)
}

public string Decrypt(string plainText) {
//(...)
}

static byte[] HmacSHA256(String data) {
//(...)
}
}

现在这将允许加密抽象 IEncrypter根据需要连同它自己的依赖项一起注入(inject)。即IOptions<TOption> .

如果打算成为唯一的加密服务,则在启动时将其注册为单例

services.AddSingleton<IEncrypter, Encrypter>();

关于c# - 将 IOptions<> 注入(inject)静态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117108/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com