ASP. NET Core implements automatic dependency injection

  • 2021-11-29 06:42:36
  • OfStack

Directory definition 1 enumeration defines 3 injection types. Scan all dll in the running directory, and use automatic dependency injection function for automatic injection

When developing. NET Core web services, we used to use our own dependency injection container for injection.

Therefore, a very frequent repetitive action will be carried out: define an interface- > Write implementation classes- > Injection

Sometimes I forget to write Add, see the error on the screen, and then instantly react and forget to inject it. Quickly fill in the sentence serviceCollection. AddXXX

Although there are many open source frameworks that have implemented similar work, such as AutoFac, Unity and other dependency injection frameworks. But these libraries are too large, and I personally prefer lightweight implementations.

Define 1 enumeration


 
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public class AutoInjectAttribute : Attribute
    {
        public AutoInjectAttribute(Type interfaceType, InjectType injectType)
        {
            Type = interfaceType;
            InjectType = injectType;
        }
 
        public Type Type { get; set; }
 
        /// <summary>
        ///  Injection type 
        /// </summary>
        public InjectType InjectType { get; set; }
    }
 

Define 3 injection types


 
/// <summary>
    ///  Injection type 
    /// </summary>
    public enum InjectType
    {
        Scope,
        Single,
        Transient
    }
 

Scan all dll in the running directory for automatic injection


 
/// <summary>
    ///  Automatic dependency injection 
    /// </summary>
    public static class AutoInject
    {
        /// <summary>
        ///  Automatically inject all assemblies with InjectAttribute Label 
        /// </summary>
        /// <param name="serviceCollection"></param>
        /// <returns></returns>
        public static IServiceCollection AddAutoDi(this IServiceCollection serviceCollection)
        {
            var path = AppDomain.CurrentDomain.BaseDirectory;
            var assemblies = Directory.GetFiles(path, "*.dll").Select(Assembly.LoadFrom).ToList();
            foreach (var assembly in assemblies)
            {
                var types = assembly.GetTypes().Where(a => a.GetCustomAttribute<AutoInjectAttribute>() != null)
                    .ToList();
                if (types.Count <= 0) continue;
                foreach (var type in types)
                {
                    var attr = type.GetCustomAttribute<AutoInjectAttribute>();
                    if (attr?.Type == null) continue;
                    switch (attr.InjectType)
                    {
                        case InjectType.Scope:
                            serviceCollection.AddScoped(attr.Type, type);
                            break;
                        case InjectType.Single:
                            serviceCollection.AddSingleton(attr.Type, type);
                            break;
                        case InjectType.Transient:
                            serviceCollection.AddTransient(attr.Type, type);
                            break;
                        default:
                            throw new ArgumentOutOfRangeException();
                    }
                }
            }
 
            return serviceCollection;
        }
    }
 

Using Automatic Dependency Injection


 
   public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoDi();
        }
 

 
  public interface ITest
    {
        string Say();
    }
 
    [AutoInject(typeof(ITest),InjectType.Scope)]
    public class Test : ITest
    {
        public String Say()
        {
            return "test:"+DateTime.Now.ToString();
        }
    }
 

Run the program again, all of which are pasted with AutoInject Will be injected into the dependency injection container of asp. net core.

These are the details of ASP. NET Core automatic dependency injection. For more information on ASP. NET Core automatic dependency injection, please pay attention to other related articles on this site!


Related articles: