NET CORE 数据访问层服务自动注册类封装和使用源码-AutoFac
项目使用三层结构
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"; } } }