2021年6月26日 星期六

ASP.net Core 3 DI 自動註冊

在Asp.net core會開始使用DI
每次都會忘記註冊,發生錯誤才會發現,我看同事好像也很有耐心的一個一個的註冊
耐心雖然是種美德,但我個人比較懶惰,於是弄了一個DI自動註冊
先建立一個擴展

public static class NativeInjectorConfig
    {
        public static void RegisterServices(this IServiceCollection services)
        {
            //繼承ServiceBase的自動註冊
            services.RegisterInheritedTypes(typeof(ServiceBase).Assembly, typeof(ServiceBase));
        }

        public static void RegisterInheritedTypes(this IServiceCollection container, Assembly assembly, Type baseType)
        {
            var allTypes = assembly.GetTypes();
            var baseInterfaces = baseType.GetInterfaces();
            foreach (var type in allTypes)
            {
                if (type.BaseType != null && type.BaseType.GenericEq(baseType))
                {
                    var typeInterface = type.GetInterfaces().FirstOrDefault(x => !baseInterfaces.Any(bi => bi.GenericEq(x)));
                    if (typeInterface == null)
                    {
                        continue;
                    }
                    container.AddScoped(typeInterface, type);
                }
            }
        }

        public static bool GenericEq(this Type type, Type toCompare)
        {
            return type.Namespace == toCompare.Namespace && type.Name == toCompare.Name;
        }
    }


然後再到startup加入

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

所以以上只要繼承ServerBase類別就會被偵測到自動註冊

沒有留言:

張貼留言