ASP.NET Core 자동 종속 주입 구현

개발 중입니다.NET Core 웹 서비스를 사용할 때, 우리는 자체 의존 주입 용기를 사용하여 주입하는 것에 익숙하다.
그래서 자주 반복적인 동작을 합니다. 인터페이스 정의->쓰기 실현 클래스->주입
때때로 Add를 쓰는 것을 잊어버리고 화면에 잘못 보고된 것을 보고 멍한 표정을 지으며 순간적으로 반응하여 주입을 잊어버리는 경우도 있다.빨리 서비스 컬렉션을 보충하세요.AddXX
많은 개원 프레임워크가 이미 유사한 작업을 실현했다고 말하지만, 예를 들어 AutoFac, Unity 등은 주입 프레임워크에 의존한다.그러나 이 창고들은 모두 너무 방대하기 때문에 나는 개인적으로 경량급의 실현을 좋아한다.

매거 정의


 
[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>
        ///  
        /// </summary>
        public InjectType InjectType { get; set; }
    }
 

세 가지 주입 유형 정의


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

실행 디렉터리에 있는 모든 dll을 스캔하여 자동 주입합니다


 
/// <summary>
    ///  
    /// </summary>
    public static class AutoInject
    {
        /// <summary>
        ///  InjectAttribute 
        /// </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;
        }
    }
 

자동 의존 주입 기능 사용


 
   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();
        }
    }
 
다시 프로그램을 실행하면 모든 부착AutoInject의 모든 실현 클래스가 asp에 주입됩니다.net 코어의 의존은 용기에 주입됩니다.
지금까지 ASP였습니다.NET Core 구현 자동 종속 주입의 상세한 내용, ASP에 대한 추가 정보.NET Core는 자동으로 주입된 자료에 의존합니다. 저희의 다른 관련 글에 주목하세요!

좋은 웹페이지 즐겨찾기