首页 > 解决方案 > 依赖注入到 {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

标签: c#.net.net-coredependency-injection.net-5

解决方案


无需使用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进行所有必要的连接以解决依赖关系、实例化类并将其注入属性。


推荐阅读