这是在 asp.net-core 的内置 DI 中自动化用户定义服务导入的正确方法吗

IS this the right way to automate the user defined service import in Built in DI in asp.net-core

我创建了一个扩展方法,用于添加在 DI 范围内的特定命名空间下定义的所有服务。效果不错。

public static class ServiceCollectionExtensions
{
    public static void AddScopedImplementations(this IServiceCollection services)
    {           
        foreach (Type type in Assembly.GetEntryAssembly().GetTypes()
          .Where(t => t.Namespace == "ServerAPI.Services")
          .Where(t => !t.GetTypeInfo().IsDefined(typeof(CompilerGeneratedAttribute),true))
          .Where(t => t.GetTypeInfo().IsClass))
        {
            services.AddScoped(type.GetTypeInfo().GetInterface("I" + type.Name), type);
        }
    }       
}

我的问题是:在 asp.net-core 的内置 DI 中这样做是正确的方法吗?

就像你说的,它有效。但是,它会将您锁定在 "ServerAPI.Services" 名称空间中。您还必须为每个 class 提供一个以 "I" 开头的同名接口,在大多数情况下这不是必需的。您还为每个依赖项提供了范围内的生命周期,但注册通常应该是暂时的,除非有理由不这样做。

换句话说,此实现将限制您使用框架的灵活性。如果你对此没问题,那可能没问题。