百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

仿ABP实现模块注入方法(adp模块)

bigegpt 2024-08-02 10:45 3 浏览

ABP的模块注入非常不错,但是ABP太臃肿了,单独的模块或者功能不能抽出来单独使用,所以就想自己实现一个模块注入方法。

ABP的模块注入原理,是程序启动时扫描所有dll模块,进行批量注入,下面是实现方法。

一、模块抽象类

查看代码

二、每个子项目下添加DependencyModule类

查看代码

namespace Core
{
    public class DependencyModule : ICoreModule
    {
        public override void Register()
        {
            //可以根据启动项目/项目环境来判断注入,例如单元测试项目
            if (this.CurrentDomainName == "UnitTest" || this.IsDevelopment)
            {
                AutofacFactory.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());
                AutofacFactory.RegisterTypeAs(typeof(IAuthContext), typeof(AuthContext));
            }
            else 
            {
                AutofacFactory.RegisterAssemblyTypes(typeof(BaseRepository<>).Assembly,
                    x => x.IsClass && !x.IsInterface,
                    x => x.BaseType.IsGenericType && x.BaseType.GetGenericTypeDefinition() == typeof(BaseRepository<>));

                AutofacFactory.RegisterAssemblyTypes(typeof(BaseEs<>).Assembly,
                    x => x.IsClass && !x.IsInterface,
                    x => x.BaseType.IsGenericType && x.BaseType.GetGenericTypeDefinition() == typeof(BaseEs<>));
            }
        }
    }
}

查看代码


namespace ServerApi
{
    public class DependencyModule : ICoreModule
    {
        public override void Register()
        {
            AutofacFactory.RegisterAssemblyTypes(typeof(Startup).Assembly,
                             x => x.IsClass && !x.IsInterface,
                             x => x.BaseType.IsGenericType && x.BaseType.GetGenericTypeDefinition() == typeof(IHandler<>));
        }
    }
}

三、项目启动时,注入autofac容器

1、.netcore2.1

关键代码 return new AutofacServiceProvider(AutofacExt.InitAutofac(services));

查看代码


namespace WebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration, IOptions<AppSetting> appConfiguration)
        {
            Configuration = configuration;
            _appConfiguration = appConfiguration;
        }

        public IConfiguration Configuration { get; }
        public IOptions<AppSetting> _appConfiguration;
        
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<AppSetting>(Configuration.GetSection("AppSetting"));
            services.AddMvc(config =>
            {
                config.Filters.Add<BasicFrameFilter>();
            })
            .AddControllersAsServices()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMemoryCache();
            services.AddCors();
            var dbType = ((ConfigurationSection)Configuration.GetSection("AppSetting:DbType")).Value;
            if (dbType == Define.DBTYPE_SQLSERVER)
            {
                services.AddDbContext<BasicFrameDBContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DBContext")));
            }
            else  //mysql
            {
                services.AddDbContext<BasicFrameDBContext>(options =>
                    options.UseMySql(Configuration.GetConnectionString("DBContext")));
            }
            services.AddHttpClient();

            return new AutofacServiceProvider(AutofacExt.InitAutofac(services));
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(route =>
            {
                route.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

                route.MapRoute(
                name: "areas",
                template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
            });

        }
    }
}

2、.netcore3.1

关键代码

.UseServiceProviderFactory(new AutofacServiceProviderFactory());

AutofacFactory.InitAutofac(builder);
builder.RegisterBuildCallback(scope =>
{
AutofacFactory.SetContainer((IContainer)scope);
});

查看代码


    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
               .UseServiceProviderFactory(new AutofacServiceProviderFactory());
    }

查看代码


    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddControllersAsServices();

            services.AddControllers()
                    .AddNewtonsoftJson(options =>
                    {
                        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();//修改属性名称的序列化方式,首字母小写
                        options.SerializerSettings.Converters.Add(new DateTimeConverter());//修改时间的序列化方式
                        options.SerializerSettings.Converters.Add(new LongConverter());
                    });

            services.AddOptions();
            services.AddMemoryCache();
            services.AddCors(options => options.AddPolicy("cors", builder => { builder.AllowAnyMethod().SetIsOriginAllowed(_ => true).AllowAnyHeader().AllowCredentials(); }));
            services.AddSignalR();
        }

        //Autofac注册
        public void ConfigureContainer(ContainerBuilder builder)
        {
            AutofacFactory.InitAutofac(builder);
            builder.RegisterBuildCallback(scope =>
            {
                AutofacFactory.SetContainer((IContainer)scope);
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment() || env.IsEnvironment("Debug"))
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("cors");
            app.UseWebSockets();
            //错误拦截中间件
            app.UseMiddleware<ExceptionMiddleware>();

            app.UseHttpsRedirection();
            app.UseStaticFiles();            
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();     
                endpoints.MapHub<MessageHub>("/MessageHub");
                endpoints.Map("/", context =>
                {
                    context.Response.Redirect(#34;/api/Home/Index");
                    return Task.CompletedTask;
                });
            });
        }
    }

四、AutofacFactory类

查看代码


    public static class AutofacFactory
    {
        private static IContainer _container;
        private static ContainerBuilder _builder;

        static AutofacFactory()
        {
        }

        public static IContainer InitAutofac(IServiceCollection services)
        {
            _builder = new ContainerBuilder();

            RegisterAllModule();

            if (services.All(u => u.ServiceType != typeof(IHttpContextAccessor)))
            {
                services.AddScoped(typeof(IHttpContextAccessor), typeof(HttpContextAccessor));
            }

            _builder.Populate(services);
            _container = _builder.Build();
            return _container;
        }

        public static IContainer InitAutofac()
        {
            _container = _builder.Build();
            return _container;
        }

        public static void InitAutofac(ContainerBuilder builder)
        {
            _builder = builder;
            RegisterAllModule();
        }

        public static void SetContainer(IContainer container)
        {
            _container = container;
        }

        public static IContainer GetContainer()
        {
            return _container;
        }

        public static ContainerBuilder GetBuilder()
        {
            return _builder;
        }

        public static void RegisterAssemblyTypes(params Assembly[] assemblies)
        {
            _builder.RegisterAssemblyTypes(assemblies);
        }

        public static void RegisterAssemblyTypes(Assembly assemblie, params Func<Type, bool>[] predicates)
        {
            var regBuilder = _builder.RegisterAssemblyTypes(assemblie);
            foreach (var pre in predicates)
            {
                regBuilder.Where(pre);
            }
        }

        public static void RegisterTypeAs(Type iServiceType, Type implementationType, AutofacLifetime lifetime = AutofacLifetime.InstancePerDependency)
        {
            var regbuilder = _builder.RegisterType(implementationType).As(iServiceType);
            if (lifetime == AutofacLifetime.SingleInstance)
            {
                regbuilder.SingleInstance();
            }
            else if (lifetime == AutofacLifetime.InstancePerLifetimeScope)
            {
                regbuilder.InstancePerLifetimeScope();
            }
        }

        public static void RegisterType(Type serviceType, AutofacLifetime lifetime = AutofacLifetime.InstancePerDependency)
        {
            var regbuilder = _builder.RegisterType(serviceType);
            if (lifetime == AutofacLifetime.SingleInstance)
            {
                regbuilder.SingleInstance();
            }
            else if (lifetime == AutofacLifetime.InstancePerLifetimeScope)
            {
                regbuilder.InstancePerLifetimeScope();
            }
        }

        /// <summary>
        /// 泛型类型注册
        /// </summary>
        public static void RegisterGeneric(Type iServiceType, Type implementationType, AutofacLifetime lifetime = AutofacLifetime.InstancePerDependency)
        {
            var regbuilder = _builder.RegisterGeneric(implementationType).As(iServiceType);
            if (lifetime == AutofacLifetime.SingleInstance)
            {
                regbuilder.SingleInstance();
            }
            else if (lifetime == AutofacLifetime.InstancePerLifetimeScope)
            {
                regbuilder.InstancePerLifetimeScope();
            }
        }

        public static void RegisterGeneric(Type serviceType, AutofacLifetime lifetime = AutofacLifetime.InstancePerDependency)
        {
            var regbuilder = _builder.RegisterGeneric(serviceType);
            if (lifetime == AutofacLifetime.SingleInstance)
            {
                regbuilder.SingleInstance();
            }
            else if (lifetime == AutofacLifetime.InstancePerLifetimeScope)
            {
                regbuilder.InstancePerLifetimeScope();
            }
        }

        public static void RegisterType<iserviceType, implementationType>(AutofacLifetime lifetime = AutofacLifetime.InstancePerDependency)
        {
            var regbuilder = _builder.RegisterType<implementationType>().As<iserviceType>();
            if (lifetime == AutofacLifetime.SingleInstance)
            {
                regbuilder.SingleInstance();
            }
            else if (lifetime == AutofacLifetime.InstancePerLifetimeScope)
            {
                regbuilder.InstancePerLifetimeScope();
            }
        }

        public static void Register<serviceType>(object obj, AutofacLifetime lifetime = AutofacLifetime.InstancePerDependency)
        {
            var regbuilder = _builder.Register(x => obj).As<serviceType>();
            if (lifetime == AutofacLifetime.SingleInstance)
                regbuilder.SingleInstance();
            else if (lifetime == AutofacLifetime.InstancePerLifetimeScope)
                regbuilder.InstancePerLifetimeScope();
        }

        public static T Resolve<T>()
        {
            return _container.Resolve<T>();
        }

        public static object Resolve(Type type)
        {
            return _container.Resolve(type);
        }

        /// <summary>
        /// 注册全部模块
        /// </summary>
        public static void RegisterAllModule(params string[] dllnames)
        {
            var assembles = DependencyContext.Default.RuntimeLibraries.Select(x => x);
            if (dllnames.Count() > 0)
            {
                foreach (string dllname in dllnames)
                {
                    assembles = assembles.Where(o => o.Name.StartsWith(dllname));
                }
                var dlls = assembles.Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
            }
            else
            {
                var dlls = assembles.Where(o => o.Type == "project")
                                    .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
            }

            //根据抽象类查找
            var types = AppDomain.CurrentDomain.GetAssemblies()
                        .SelectMany(a => a.GetTypes().Where(t => t.BaseType == typeof(ICoreModule) && t.BaseType.IsAbstract))
                        .ToArray();

            //根据接口查找
            //var types = AppDomain.CurrentDomain.GetAssemblies()
            //            .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(ICoreModule))))
            //            .ToArray();

            foreach (var t in types)
            {
                var instance = (ICoreModule)Activator.CreateInstance(t);
                instance.Register();
            }
        }
    }

    /// <summary>
    /// 生命周期
    /// </summary>
    public enum AutofacLifetime
    {
        /// <summary>
        /// 默认生命周期,每次请求都创建新的对象
        /// </summary>
        InstancePerDependency,
        /// <summary>
        /// 每次都用同一个对象
        /// </summary>
        SingleInstance,
        /// <summary>
        /// 同一个Lifetime生成的对象是同一个实例
        /// </summary>
        InstancePerLifetimeScope
    }

相关推荐

得物可观测平台架构升级:基于GreptimeDB的全新监控体系实践

一、摘要在前端可观测分析场景中,需要实时观测并处理多地、多环境的运行情况,以保障Web应用和移动端的可用性与性能。传统方案往往依赖代理Agent→消息队列→流计算引擎→OLAP存储...

warm-flow新春版:网关直连和流程图重构

本期主要解决了网关直连和流程图重构,可以自此之后可支持各种复杂的网关混合、多网关直连使用。-新增Ruoyi-Vue-Plus优秀开源集成案例更新日志[feat]导入、导出和保存等新增json格式支持...

扣子空间体验报告

在数字化时代,智能工具的应用正不断拓展到我们工作和生活的各个角落。从任务规划到项目执行,再到任务管理,作者深入探讨了这款工具在不同场景下的表现和潜力。通过具体的应用实例,文章展示了扣子空间如何帮助用户...

spider-flow:开源的可视化方式定义爬虫方案

spider-flow简介spider-flow是一个爬虫平台,以可视化推拽方式定义爬取流程,无需代码即可实现一个爬虫服务。spider-flow特性支持css选择器、正则提取支持JSON/XML格式...

solon-flow 你好世界!

solon-flow是一个基础级的流处理引擎(可用于业务规则、决策处理、计算编排、流程审批等......)。提供有“开放式”驱动定制支持,像jdbc有mysql或pgsql等驱动,可...

新一代开源爬虫平台:SpiderFlow

SpiderFlow:新一代爬虫平台,以图形化方式定义爬虫流程,不写代码即可完成爬虫。-精选真开源,释放新价值。概览Spider-Flow是一个开源的、面向所有用户的Web端爬虫构建平台,它使用Ja...

通过 SQL 训练机器学习模型的引擎

关注薪资待遇的同学应该知道,机器学习相关的岗位工资普遍偏高啊。同时随着各种通用机器学习框架的出现,机器学习的门槛也在逐渐降低,训练一个简单的机器学习模型变得不那么难。但是不得不承认对于一些数据相关的工...

鼠须管输入法rime for Mac

鼠须管输入法forMac是一款十分新颖的跨平台输入法软件,全名是中州韵输入法引擎,鼠须管输入法mac版不仅仅是一个输入法,而是一个输入法算法框架。Rime的基础架构十分精良,一套算法支持了拼音、...

Go语言 1.20 版本正式发布:新版详细介绍

Go1.20简介最新的Go版本1.20在Go1.19发布六个月后发布。它的大部分更改都在工具链、运行时和库的实现中。一如既往,该版本保持了Go1的兼容性承诺。我们期望几乎所...

iOS 10平台SpriteKit新特性之Tile Maps(上)

简介苹果公司在WWDC2016大会上向人们展示了一大批新的好东西。其中之一就是SpriteKitTileEditor。这款工具易于上手,而且看起来速度特别快。在本教程中,你将了解关于TileE...

程序员简历例句—范例Java、Python、C++模板

个人简介通用简介:有良好的代码风格,通过添加注释提高代码可读性,注重代码质量,研读过XXX,XXX等多个开源项目源码从而学习增强代码的健壮性与扩展性。具备良好的代码编程习惯及文档编写能力,参与多个高...

Telerik UI for iOS Q3 2015正式发布

近日,TelerikUIforiOS正式发布了Q32015。新版本新增对XCode7、Swift2.0和iOS9的支持,同时还新增了对数轴、不连续的日期时间轴等;改进TKDataPoin...

ios使用ijkplayer+nginx进行视频直播

上两节,我们讲到使用nginx和ngixn的rtmp模块搭建直播的服务器,接着我们讲解了在Android使用ijkplayer来作为我们的视频直播播放器,整个过程中,需要注意的就是ijlplayer编...

IOS技术分享|iOS快速生成开发文档(一)

前言对于开发人员而言,文档的作用不言而喻。文档不仅可以提高软件开发效率,还能便于以后的软件开发、使用和维护。本文主要讲述Objective-C快速生成开发文档工具appledoc。简介apple...

macOS下配置VS Code C++开发环境

本文介绍在苹果macOS操作系统下,配置VisualStudioCode的C/C++开发环境的过程,本环境使用Clang/LLVM编译器和调试器。一、前置条件本文默认前置条件是,您的开发设备已...