netcore 依据注解自动注入

            DbCtxt.ConnStr = Configuration.GetSection("ConnectionString").Value;

            // 根据类是否添加注解[IsService]来自动注入
            var assm = new[] { typeof(Program).Assembly, typeof(DbCtxt).Assembly };
            foreach (var ass in assm)
            {
                var types = ass.GetTypes();
                foreach (var typ in types)
                {
                    var typeInfo = typ.GetTypeInfo();
                    if (typeInfo.IsDefined(typeof(IsService)))
                    {
                        services.AddScoped(typ);
                        var interfaces = typeInfo.ImplementedInterfaces;
                        foreach (var item in interfaces)
                        {
                            services.AddScoped(item, typ);
                        }
                    }
                }
            }

 

posted on 2020-09-23 07:44  jonney_wang  阅读(594)  评论(0编辑  收藏  举报

导航