.NET CORE3.1使用内置IOC自动注入

在.NET CORE中注入时需要在Startup的ConfigureServices中写
services.AddScoped<IServices, Services>();

项目如果比较大,每次写起来就会很麻烦,所以需要让程序可以自动注入

首先新建两个接口 IDenpendency,IDenpendcySingleton,或者使用特性也可以。
    /// <summary>
    /// 使用Scoped方式注入
    /// </summary>
    public interface IDenpendency
    {
    }

    /// <summary>
    /// 使用Singleton方式注入
    /// </summary>
    public interface IDenpendcySingleton
    {
    }
    /// <summary>
    /// 业务接口继承其中一个
    /// </summary>
    public interface IStockInAppService: IDenpendency
    {
    }
在web项目中新建一个DIDataService的静态类
    public static class DIDataService
    {
        public static IServiceCollection AddDataService(this IServiceCollection services)
        {
            #region 处理依赖注入
            var transientType = typeof(IDenpendency); //每次新建
            var singletonType = typeof(IDenpendcySingleton); //全局唯一

            var allTypes = AppDomain.CurrentDomain.GetAssemblies()
                //.FirstOrDefault(t => t.FullName.Contains("AbpCore.InterfaceServices.Application"))
                ////获取所有对象
                //.GetTypes()
                .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(transientType) || t.GetInterfaces().Contains(singletonType)));

            //class的程序集
            var implementTypes = allTypes.Where(x => x.IsClass).ToArray();
            //接口的程序集
            var interfaceTypes = allTypes.Where(x => x.IsInterface).ToArray();

            foreach (var implementType in implementTypes)
            {
                var interfaceType = interfaceTypes.FirstOrDefault(x => x.IsAssignableFrom(implementType));
                //class有接口,用接口注入
                if (interfaceType != null)
                {
                    //判断用什么方式注入
                    if (interfaceType.GetInterfaces().Contains(transientType))
                    {
                        services.AddScoped(interfaceType, implementType);
                    }
                    else if (interfaceType.GetInterfaces().Contains(singletonType))
                    {
                        services.AddSingleton(interfaceType, implementType);
                    }
                }
                else //class没有接口,直接注入class
                {
                    //判断用什么方式注入
                    if (implementType.GetInterfaces().Contains(transientType))
                    {
                        services.AddTransient(implementType);
                    }
                    else if (implementType.GetInterfaces().Contains(singletonType))
                    {
                        services.AddSingleton(implementType);
                    }
                }
            }
            #endregion
            return services;
        }
    }
最后在Startup的ConfigureServices中注入DIDataService
services.AddDataService();

这样就可以自动注入了,不用再操心注入啦

上一篇:算法-Contains Duplicate-存在重复元素


下一篇:indexOf()与contains()的区别