简体   繁体   English

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

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

I have created an extension method for adding all services which are defined under a particular namespace as scoped in DI. 我创建了一个扩展方法,用于添加在DI中定义的特定名称空间下定义的所有服务。 It works well. 它运作良好。

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);
        }
    }       
}

My question is: Is this the right way to do that in the built DI in asp.net-core? 我的问题是:这是在asp.net-core的内置DI中执行此操作的正确方法吗?

Like you said, it works. 就像你说的那样。 But, it locks you into the "ServerAPI.Services" namespace. 但是,它将您锁定在“ ServerAPI.Services”命名空间中。 You also have to give every single class an interface of the same name that starts with "I", which in most cases should not be necessary. 您还必须为每个类提供一个以“ I”开头的相同名称的接口,在大多数情况下,这是不必要的。 You're also giving every dependency a scoped lifetime, but registrations should usually be transient unless there's a reason for them not to be. 您还为每个依赖项提供了范围内的生存期,但是注册通常应该是暂时的,除非有理由不这样做。

In other words, this implementation will restrict your flexibility with the framework. 换句话说,此实现将限制您使用框架的灵活性。 If you're okay with that, then it's probably fine. 如果您对此表示满意,那可能很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM