简体   繁体   中英

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. 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?

Like you said, it works. But, it locks you into the "ServerAPI.Services" namespace. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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