c# - 依赖注入到 {get; 设置;} 属性
问题描述
我想知道如何设置我的依赖注入以将依赖注入到具有公共 getter 和 setter ({get; set}) 的属性中。
所以,一个例子是:
namespace Dexter.Services {
public class CommandHandlerService : InitializableModule {
public CommandService CommandService { get; set; }
}
}
使用以下依赖注入器:
namespace Dexter {
public static class InitializeDependencies {
public static async Task Main() {
ServiceCollection ServiceCollection = new();
CommandService CommandService = new();
ServiceCollection.AddSingleton(CommandService);
Assembly.GetExecutingAssembly().GetTypes()
.Where(Type => Type.IsSubclassOf(typeof(InitializableModule)) && !Type.IsAbstract)
.ToList().ForEach(
Type => ServiceCollection.TryAddSingleton(Type)
);
ServiceProvider = ServiceCollection.BuildServiceProvider();
// Initialization stuff.
}
}
}
在此示例中,我希望 CommandService 自动注入到属性中。
我知道这是可能的,因为 Discord.NET 能够做到这一点,而且我很想坚持使用相同的代码风格。
(Discord.NET:https://docs.stillu.cc/guides/commands/dependency-injection.html)
谢谢!<3
解决方案
无需使用Quickwire NuGet 包更换默认 DI 容器 ( IServiceProvider
)即可完成此操作。
只需使用[RegisterService]
属性装饰您的服务并添加[InjectService]
到属性中。不需要接口。
[RegisterService(ServiceLifetime.Singleton)]
public class CommandHandlerService {
[InjectService]
public CommandService CommandService { get; set; }
}
现在从您的主要功能,只需调用ScanCurrentAssembly
:
public static async Task Main() {
ServiceCollection ServiceCollection = new();
ServiceCollection.ScanCurrentAssembly();
ServiceProvider = ServiceCollection.BuildServiceProvider();
// Initialization stuff.
}
在幕后,ScanCurrentAssembly
进行所有必要的连接以解决依赖关系、实例化类并将其注入属性。
推荐阅读
- ruby-on-rails - docker compose rails 6 example with mailcatcher 不起作用
- c# - 如何通过 COM 互操作将 VBA 变体数组数据类型传递给 C# 方法
- bash - 尝试从 Raspberry PI DHT 22 传感器的输出中提取数字
- python - Python 批量求和数据框列
- asp.net-core-3.1 - 无法加载类型“System.ServiceModel.Activation.VirtualPathExtension”
- azure-functions - 如何在 macOS 上运行 Azure Functions 3.0
- oracle - 在Oracle中运行时在相同模式的两个表之间切换视图
- cygwin - 在非主文件夹中打开 Cygwin 终端时,如何阻止它忘记环境?
- python - 如何减小包含 python 实用程序的 nodejs 容器的大小
- sqlalchemy - flask_sqlalchemy 中具有相同表名的多数据库