首页 > 编程语言 >数据访问层服务自动注册类封装和使用源码-AutoFac

数据访问层服务自动注册类封装和使用源码-AutoFac

时间:2023-01-29 12:11:58浏览次数:47  
标签:AutoFac 封装 Admin app public 源码 services using Microsoft

项目使用三层结构
RepositoryIocFactory
using System;
using System.Reflection;
using Autofac;

namespace CommonHelper.AutoInject.Repository
{
    public class RepositoryIocFactory
    {
        private static IContainer _container = null;

        private static object _locker = new object();
       //根据命名空间自动注册类名以Repository结尾的实现类,参数是数据访问层的命名空间
        public static void AutoRegisterService(string namespaceNameRegister)
        {
            if (_container != null)
            {
                return;
            }

            lock (_locker)
            {
                if (_container == null)
                {
                    ContainerBuilder containerBuilder = new ContainerBuilder();
                    Assembly assembly = Assembly.Load(namespaceNameRegister);
                    (from t in containerBuilder.RegisterAssemblyTypes(assembly)
                     where t.Name.EndsWith("Repository")
                     where !t.Name.Contains("BaseRepositorycs")
                     select t).AsImplementedInterfaces().InstancePerDependency();
                    _container = containerBuilder.Build();
                }
            }
        }
     //获取服务实例对象
        public static T GetRegisterImp<T>()
        {
            T val = default(T);
            using ILifetimeScope context = _container.BeginLifetimeScope();
            return context.Resolve<T>();
        }
    }
}

在Startup.cs类中调用AutoRegisterService方法实现注册

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LD.Admin.Models;
using Microsoft.OpenApi.Models;
using System.Reflection;
using System.IO;
using Swashbuckle.AspNetCore.SwaggerUI;
using CommonHelper.AutoInject.Service;
using LD.Admin.Service.RegisterService;
using LD.Admin.Repository.Factory;
using LD.Admin.Api.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using LD.Admin.Common;
using Microsoft.AspNetCore.SignalR;
using CommonHelper.AutoInject.Repository;

namespace LD.Admin.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            //注册全局Configuration对象
            ConfigurationManager.Configure(Configuration);
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "XX后台管理服务接口", Version = "v1" });
                // 获取xml文件名
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                // 获取xml文件路径
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                // 添加控制器层注释,true表示显示控制器注释
                c.IncludeXmlComments(xmlPath, true);
                c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                c.DocumentFilter<HiddenApiFilter>();
            });
            services.Configure<TokenManagementModel>(Configuration.GetSection("JwtTokenConfig"));
            var token = Configuration.GetSection("JwtTokenConfig").Get<TokenManagementModel>();
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
                    ValidIssuer = token.Issuer,
                    ValidAudience = token.Audience,
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

            services.AddScoped<IAuthenticateService, TokenAuthenticationService>();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //services.AddSingleton<NotificationHub>();
            //services.AddSingleton<ChatHub>();
            //"LD.Admin.Repository"
            //RepositoryFactory.AutoRegisterService(string.Empty, "LD.Admin.Repository");
            //RegisterServiceIoc.Register(services);
            //services.AddAutoDi();
            services.AddAutoDiService("LD.Admin.Service");
            //services.AddAutoDiService("LD.Admin.Repository");
            //AutoFacFactory.AutoRegisterService("LD.Admin.Repository");
            //调用AutoRegisterService方法实现数据访问层服务自动注册
            RepositoryIocFactory.AutoRegisterService("LD.Admin.Repository");
            //添加对AutoMapper的支持,会查找所有程序集中继承了 Profile 的类
            // 配置AutoMapper
            services.AddAutoMapper(typeof(AutoMapperConfigs));
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddControllers();
            services.AddSignalR();

            //跨域
            var corsstring = Configuration.GetSection("Cors").Value;
            string[] corsarray = corsstring.Split(',');

            services.AddCors(options => options.AddPolicy("CorsPolicy",
            builder =>
            {
                builder.AllowAnyMethod().AllowAnyHeader()
                       .WithOrigins(corsarray)
                       .AllowCredentials();
            }));

            //var assbembly = AppDomain.CurrentDomain.GetAssemblies().ToList();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //注入请求。
            ServiceLocator.SetServices(app.ApplicationServices);
            //添加Swagger有关中间件
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "AdminAPI  v1");
                c.RoutePrefix = string.Empty;
                c.DocExpansion(DocExpansion.None);
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            
            app.UseHttpsRedirection();

            app.UseRouting();
            app.UseCors("CorsPolicy");
            //启用认证
            app.UseAuthentication();
            //启用授权
            app.UseAuthorization();
            //var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            var apiUrlConfig = Configuration.GetSection("ApiUrl").Value;
            app.UseEndpoints(endpoints =>
            {
                //endpoints.MapHub<ChatHub>("/chatHub");
                //endpoints.MapHub<ChatHub>("/chatHub").RequireCors(t => t.WithOrigins(new string[] { "http://localhost:8080" }).AllowAnyMethod().AllowAnyHeader().AllowCredentials());
                endpoints.MapHub<ChatHub>("/chatHub").RequireCors(t => t.WithOrigins(new string[] { apiUrlConfig }).AllowAnyMethod().AllowAnyHeader().AllowCredentials());
                //endpoints.MapHub<ChatHub>("/notifyHub").RequireCors(t => t.WithOrigins(new string[] { apiUrlConfig }).AllowAnyMethod().AllowAnyHeader().AllowCredentials());
                endpoints.MapControllers();
            });
        }
    }
}

数据访问层实现类

/// <summary>
    /// 行业表 的数据访问层实现类
    /// </summary>
    public class IndustryRepository : BaseRepository<int, IndustrySearchModel, IndustryModel>, IIndustryRepository
    {
        public override string ClassName
        {
            get { return "IndustryRepository"; }
        }

        public override string TableName
        {
            get { return "Industry"; }
        }
    }

在业务层的调用方法

/// <summary>
    /// 行业表 业务逻辑层接口 实现类
    /// </summary>
    [AutoInject(typeof(IIndustryService), InjectType.Scope)]
    public class IndustryService : BaseService<IIndustryRepository,int, IndustrySearchModel, IndustryModel>, IIndustryService
    {
        protected override IIndustryRepository Service
        {
            //get { return RepositoryFactory.Industry; }
            get { return RepositoryIocFactory.GetRegisterImp<IIndustryRepository>(); }
        }

        protected override string ClassName
        {
            get { return "IndustryService"; }
        }
    }

 

标签:AutoFac,封装,Admin,app,public,源码,services,using,Microsoft
From: https://www.cnblogs.com/stevenchen2016/p/17072329.html

相关文章

  • spring 源码浅析
    AliasRegistry:定义对alias的简单增删改查SimpleAliasRegistry:主要使用map作为alias的缓存,并对接口AliasRegistry进行实现SingletonBeanRegistry:定义对单例的注册及获取Bean......
  • JDBC之封装工具类(重用性方案)
    JDBC之封装工具类(重用性方案)实际JDBC使用过程中,存在大量重复代码,例如连接和数据库和关闭数据库我们需要把传统JDBC代码重构,抽取JDBC工具类,以后连接数据库,释放资源,都......
  • Java安全 - RMI源码分析
    RMI远程服务创建流程分析1、远程对象创建过程首先步入对象的构造方法下一步这里步入了父类UnicastRemoteObject的构造函数,传入一个参数port,作用是将远程对象随即发......
  • Spring源码解析
    publicvoidrefresh()throwsBeansException,IllegalStateException{synchronized(this.startupShutdownMonitor){StartupStepcontextRefres......
  • elementui表格封装
    <template><divid="commonTable"><divclass="common_table"><el-table:data="tableData"ref="multipleTable"v-loading="loading"......
  • 网络安全学习之网站源码相关知识
    架构了解 ·要知道网站的目录结构:后台目录,模板目录,数据库目录,数据库配置文件 ·要了解网站是由什么脚本编写的,常见的脚本:asp,java,javascrip,python,php,aspx。掌握相......
  • 视频直播源码,uniapp checkbox 怎么判断是否选中
    视频直播源码,uniappcheckbox怎么判断是否选中<checkbox-group@change="selfChangde"name=""><label><checkbox:checked="selfChecked"color="#DC143C"style="trans......
  • python对接API二次开发高级实战案例解析:百度地图Web服务API封装函数(行政区划区域检索
    文章目录​​前言​​​​一、IP定位​​​​1.请求URL​​​​2.获取IP定位封装函数​​​​3.输出结果​​​​二、国内天气查询​​​​1.请求url​​​​2.天气查询封装......
  • OpenMP 线程同步 Construct 实现原理以及源码分析(上)
    OpenMP线程同步Construct实现原理以及源码分析(上)前言在本篇文章当中主要给大家介绍在OpenMP当中使用的一些同步的construct的实现原理,如master,single,critica......
  • WPF鼠标、键盘、拖拽事件、用行为封装事件
    WPF鼠标、键盘、拖拽事件、用行为封装事件本文主要介绍了WPF中常用的鼠标事件、键盘事件以及注意事项,同时使用一个案例讲解了拓展事件。除此之外,本文还讲述如何用行为(Behav......