コード例 #1
0
        private static void ConfigurePersonMapping()
        {
            var config = new AutoMapper.Configuration.MapperConfigurationExpression();

            config.CreateMap <AddPersonEntity, Person>();
            Mapper.Initialize(config);
        }
コード例 #2
0
ファイル: Mapper.cs プロジェクト: kumarshyam5/NorthWindSample
 public static void Register()
 {
     AutoMapper.Configuration.MapperConfigurationExpression config = new AutoMapper.Configuration.MapperConfigurationExpression();
     config.CreateMap <Category, CategoryDTO>();
     config.CreateMap <Product, ProductDTO>();
     AutoMapper.Mapper.Initialize(config);
 }
コード例 #3
0
        protected virtual AutoMapper.Configuration.MapperConfigurationExpression GetMapperConfiguration()
        {
            var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();

            cfg.CreateMap <DishDto, Dish>();
            return(cfg);
        }
コード例 #4
0
        private static void MappingAction(AutoMapper.Configuration.MapperConfigurationExpression config, Type sourceType, Type destinationType)
        {
            Type actualSourceType      = sourceType;
            Type actualDestinationType = destinationType;

            if (sourceType.IsArray)
            {
                actualSourceType = sourceType.GetElementType();
            }

            if (destinationType.IsArray)
            {
                actualDestinationType = destinationType.GetElementType();
            }

            if (sourceType.IsGenericType && sourceType.GetGenericTypeDefinition() == typeof(List <>))
            {
                actualSourceType = sourceType.GetGenericArguments()[0];
            }

            if (destinationType.IsGenericType && destinationType.GetGenericTypeDefinition() == typeof(List <>))
            {
                actualDestinationType = destinationType.GetGenericArguments()[0];
            }

            MapProperties(config, actualSourceType, actualDestinationType);

            mi.Invoke(config, new object[] { actualSourceType, actualDestinationType });
        }
コード例 #5
0
ファイル: Global.asax.cs プロジェクト: zhaobingwang/samples
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

            #region mapper
            //var config = new AutoMapper.MapperConfiguration(cfg =>
            //{
            //    cfg.AddProfile<Book2BookDtoProfile>();
            //});
            //var mapper = config.CreateMapper();

            //AutoMapper.Mapper.Initialize(cfg =>
            //{
            //    cfg.AddProfile<Book2BookDtoProfile>();
            //});

            var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();
            cfg.AddProfile <Book2BookDtoProfile>();
            AutoMapper.Mapper.Initialize(cfg);
            #endregion
        }
コード例 #6
0
        private void AutoMapperConfigure()
        {
            var configurationExpression = new AutoMapper.Configuration.MapperConfigurationExpression();

            configurationExpression.AddProfile <PagedListMappingProfile>();

            Mapper.Initialize(configurationExpression);
        }
コード例 #7
0
        private void ConfigureMapping()
        {
            var config = new AutoMapper.Configuration.MapperConfigurationExpression();

            AutoMapperConfig.Configure(config);

            AutoMapper.Mapper.Initialize(config);
        }
コード例 #8
0
 public static void initialize()
 {
     AutoMapper.Configuration.MapperConfigurationExpression config = new AutoMapper.Configuration.MapperConfigurationExpression();
     config.CreateMap <Order, OrderEntity>();
     config.CreateMap <ServiceOrder, ServiceOrderEntity>();
     config.CreateMap <ServiceType, ServiceTypeEntities>();
     AutoMapper.Mapper.Initialize(config);
 }
コード例 #9
0
 public static void Inicializar(AutoMapper.Configuration.MapperConfigurationExpression expressaoConfiguracao)
 {
     if (!IsInicializado)
     {
         try { Mapper.Initialize(expressaoConfiguracao); Mapeador = Mapper.Instance; }
         catch { }
         IsInicializado = true;
     }
 }
コード例 #10
0
        private void SetupAutoMapper()
        {
            // setup automapper
            var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();

            cfg.CreateMap <RegisterVehicle, Vehicle>();
            cfg.CreateMap <RegisterVehicle, VehicleRegistered>()
            .ForCtorParam("messageId", opt => opt.MapFrom(c => Guid.NewGuid()));
            Mapper.Initialize(cfg);
        }
コード例 #11
0
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;


            var express = new AutoMapper.Configuration.MapperConfigurationExpression();

            express.AddProfile <DtoMappings>();
            Mapper.Initialize(express);
        }
コード例 #12
0
        /// <summary>
        /// 初始化对象映射关系
        /// </summary>
        public static void InitializeMappers()
        {
            var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();

            foreach (Type proType in AssemblyHelper.GetTypeByInterface <IAutoProfile>())
            {
                cfg.AddProfile(proType);
            }

            AutoMapper.Mapper.Initialize(cfg);
        }
コード例 #13
0
ファイル: AutomapperConfig.cs プロジェクト: zhlei616/pitstop
        public static void SetupAutoMapper()
        {
            // setup automapper
            var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();

            cfg.CreateMap <PlanMaintenanceJob, MaintenanceJobPlanned>()
            .ForCtorParam("messageId", opt => opt.MapFrom(c => Guid.NewGuid()));
            cfg.CreateMap <FinishMaintenanceJob, MaintenanceJobFinished>()
            .ForCtorParam("messageId", opt => opt.MapFrom(c => Guid.NewGuid()));
            Mapper.Initialize(cfg);
        }
コード例 #14
0
ファイル: AutomapperConfig.cs プロジェクト: ramsapkota/IMS
        private IMapper ConfigureMapper()
        {
            EncryptionService encSvc = new EncryptionService();

            AutoMapper.Configuration.MapperConfigurationExpression mapConfig = new AutoMapper.Configuration.MapperConfigurationExpression();
            MappingConfigurationBackOffice(mapConfig);
            var config = new MapperConfiguration(mapConfig);

            AutoMapper.Mapper.Initialize(mapConfig);
            return(AutoMapper.Mapper.Instance);
        }
コード例 #15
0
        private void SetupAutoMapper()
        {
            // setup automapper
            var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();

            cfg.CreateMap <CustomerRegisterVM, Customer>();
            cfg.CreateMap <VehicleRegisterVM, Vehicle>();
            cfg.CreateMap <PlanMaintenanceJobVM, MaintenanceJob>();
            //cfg.CreateMap<Vehicle, RegisterVehicle>()
            //cfg.CreateMap<VehicleManagementNewViewModel, RegisterVehicle>().ConvertUsing((vm, rv) =>
            //    new RegisterVehicle(Guid.NewGuid(), vm.Vehicle.LicenseNumber, vm.Vehicle.Brand, vm.Vehicle.Type, vm.SelectedEmailAddress));
            Mapper.Initialize(cfg);
        }
コード例 #16
0
        private void LoadIMapCustomMappings(IEnumerable <Type> types)
        {
            var maps = (from t in types
                        from i in t.GetInterfaces()
                        where typeof(IHaveCustomMappings).IsAssignableFrom(t) &&
                        !t.IsAbstract &&
                        !t.IsInterface
                        select(IHaveCustomMappings) Activator.CreateInstance(t)).ToArray();

            var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();
            //foreach (var map in maps)
            //    map.CreateMappings(cfg); // TODO (ch): This will NOT work. Only here for compilability. Need to figure out how to get to the cfg instance
        }
コード例 #17
0
        private void AutoMapperSetup(IServiceCollection services)
        {
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            var config = new AutoMapper.Configuration.MapperConfigurationExpression();

            config.AddProfile <ManagerMappingProfile>();
            config.AddProfile <DTOMappingProfile>();

            Mapper.Initialize(config);

            Mapper.AssertConfigurationIsValid();
        }
コード例 #18
0
ファイル: Startup.cs プロジェクト: zhlei616/pitstop
        private void SetupAutoMapper()
        {
            // setup automapper
            var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();

            cfg.CreateMap <Customer, RegisterCustomer>()
            .ForCtorParam("messageId", opt => opt.MapFrom(c => Guid.NewGuid()))
            .ForCtorParam("customerId", opt => opt.MapFrom(c => Guid.NewGuid()));
            cfg.CreateMap <Vehicle, RegisterVehicle>()
            .ForCtorParam("messageId", opt => opt.MapFrom(c => Guid.NewGuid()));
            cfg.CreateMap <VehicleManagementNewViewModel, RegisterVehicle>().ConvertUsing((vm, rv) =>
                                                                                          new RegisterVehicle(Guid.NewGuid(), vm.Vehicle.LicenseNumber, vm.Vehicle.Brand, vm.Vehicle.Type, vm.SelectedCustomerId));
            Mapper.Initialize(cfg);
        }
コード例 #19
0
        /// <summary>
        /// 初始化对象映射关系
        /// </summary>
        static public void RegisterAutoMapper()
        {
            var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();

            foreach (Type proType in AssemblyProvider.GetTypeByInterface <IDBAutoProfile>())
            {
                cfg.AddProfile(proType);
            }

            cfg.SourceMemberNamingConvention      = new LowerUnderscoreNamingConvention(); // 命名是小写并包含下划线
            cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();      // 帕斯卡命名规则

            Configuration = new MapperConfiguration(cfg);
            Mapper        = Configuration.CreateMapper();
        }
コード例 #20
0
        private static void CreateMap(AutoMapper.Configuration.MapperConfigurationExpression config, Type sourceType, Type destinationType)
        {
            Tuple <Type, Type> mappingKey = new Tuple <Type, Type>(sourceType, destinationType);

            if (!mappingsCache.Contains(mappingKey))
            {
                lock (locker)
                {
                    if (!mappingsCache.Contains(mappingKey) && mappingsCache.Add(mappingKey))
                    {
                        MappingAction(config, sourceType, destinationType);
                    }
                }
            }
        }
コード例 #21
0
ファイル: Startup.cs プロジェクト: yolita15/Service-Book-API
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ServiceBookContext serviceBookContext)
        {
            app.UseDefaultFiles();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();

            cfg.CreateMap <Company, CompanyDto>();
            cfg.CreateMap <User, UserDto>()
            .ForMember(dest => dest.Name, opt => opt.MapFrom(src =>
                                                             $"{src.FirstName} {src.LastName}"));
            cfg.CreateMap <Tfm, TfmDto>()
            .ForMember(dest => dest.DataToDisplay, opt => opt.MapFrom(src =>
                                                                      $"{src.Code} {src.Name}"));
            cfg.CreateMap <Object, ObjectForDropdownDto>();
            cfg.CreateMap <Object, ObjectDto>();

            cfg.CreateMap <ObjectDto, Object>()
            .ForMember(o => o.Id, od => od.MapFrom(s => s.Id))
            .ForMember(o => o.Name, od => od.MapFrom(s => s.Name))
            .ForMember(o => o.TfmId, od => od.MapFrom(s => s.TfmId))
            .ForMember(o => o.TypeId, od => od.MapFrom(s => s.TypeId))
            .ForMember(o => o.Comment, od => od.MapFrom(s => s.Comment))
            .ForMember(o => o.Longitude, od => od.MapFrom(s => s.Longitude))
            .ForMember(o => o.Latitude, od => od.MapFrom(s => s.Latitude))
            .ForMember(o => o.ObjectIdentifier, od => od.MapFrom(s => s.ObjectIdentifier))
            .ForMember(o => o.CompanyId, od => od.MapFrom(s => s.CompanyId))
            .ForMember(o => o.ImageName, od => od.MapFrom(s => s.ImageName))
            .ForAllOtherMembers(opt => opt.Ignore());


            Mapper.Initialize(cfg);

            serviceBookContext.EnsureSeedDataForContext();
            app.UseHttpsRedirection();
            app.UseCors("CorsPolicy");
            app.UseMvc();
        }
コード例 #22
0
        private static void MapProperties(AutoMapper.Configuration.MapperConfigurationExpression config, Type sourceType, Type destinationType)
        {
            PropertyInfo[] destinationProperties = GetProperties(destinationType);

            if (destinationProperties.Length > 0)
            {
                PropertyInfo[] sourceProperties = GetProperties(sourceType);

                string[] commonPropertyNames = destinationProperties.Where(dp => sourceProperties.Any(sp => sp.Name == dp.Name)).Select(property => property.Name).ToArray();

                foreach (string propertyName in commonPropertyNames)
                {
                    Type sourcePropertyType      = sourceProperties.First(sourceProperty => sourceProperty.Name == propertyName).PropertyType;
                    Type destinationPropertyType = destinationProperties.First(destinationProperty => destinationProperty.Name == propertyName).PropertyType;

                    CreateMap(config, sourcePropertyType, destinationPropertyType);
                }
            }
        }
コード例 #23
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
            .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            GlobalConfiguration.Configuration.Formatters
            .Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);

            AutoMapper.Configuration.MapperConfigurationExpression mapperConfig = new AutoMapper.Configuration.MapperConfigurationExpression();
            mapperConfig.CreateMap <Category, CategoryModel>();

            //very essential
            Mapper.Initialize(mapperConfig);
        }
コード例 #24
0
        public static IServiceCollection RegistrarAutoMapper(this IServiceCollection services, params Assembly[] assemblies)
        {
            var expressaoConfiguracao = new AutoMapper.Configuration.MapperConfigurationExpression();

            expressaoConfiguracao.AddProfiles(assemblies);
            services.AddSingleton <IMapperConfigurationExpression>(expressaoConfiguracao);

            var configuracao = new MapperConfiguration(expressaoConfiguracao);

            services.AddSingleton <MapperConfiguration>(configuracao);

            var mapper = configuracao.CreateMapper();

            services.AddSingleton <IMapper>(mapper);

            MapeamentoExtensions.Inicializar(expressaoConfiguracao);

            return(services);
        }
コード例 #25
0
        public static void RegisterMaps(this AutoMapper.Configuration.MapperConfigurationExpression config, MethodInfo[] methods)
        {
            foreach (MethodBase methodBase in methods)
            {
                IList <Instruction> instructions = MethodBaseRocks.GetInstructions(methodBase);

                foreach (Instruction instruction in instructions.Where(i => i.Operand != null && i.Operand is MethodInfo))
                {
                    MethodInfo methodInfo = instruction.Operand as MethodInfo;

                    if (methodInfo != null && methodInfo.Name.StartsWith("ILDeepCopyFromTo"))
                    {
                        Type sourceType      = methodInfo.GetParameters().First().ParameterType;
                        Type destinationType = methodInfo.ReturnType;

                        CreateMap(config, sourceType, destinationType);
                    }
                }
            }
        }
コード例 #26
0
        public void InstallServices(IServiceCollection services, IConfiguration configuration)
        {
            var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();

            cfg.AddProfile <AccountProfile>();
            cfg.AddProfile <BrojKorisnikaLogProfile>();
            cfg.AddProfile <ComboBoxProfile>();
            cfg.AddProfile <FeedsProfile>();
            cfg.AddProfile <GradoviProfile>();
            cfg.AddProfile <ObjaveProfile>();
            cfg.AddProfile <PrijavaProfile>();
            cfg.AddProfile <ReportProfile>();
            cfg.AddProfile <StatistikeProfile>();
            cfg.AddProfile <TakmicenjeProfile>();
            cfg.AddProfile <TakmicenjeVMProfile>();

            var config = new MapperConfiguration(cfg);

            var mapper = config.CreateMapper();

            services.AddSingleton(mapper);
        }
コード例 #27
0
        private static void InitializeContainer(Container container)
        {
            container.Register <IBaseControllerDependencies, BaseControllerDependencies>(Lifestyle.Scoped);
            container.RegisterConditional(typeof(ILogger),
                                          context => typeof(NLogProxy <>).MakeGenericType(context.Consumer.ImplementationType),
                                          Lifestyle.Scoped, context => true);
            container.Register <ILoggerFactory, LoggerFactory>(Lifestyle.Scoped);

            container.Register <Logger.ILogRequestContext>(() =>
            {
                var rslt = new General.WebUILogRequestContext(new HttpContextWrapper(System.Web.HttpContext.Current));
                return(rslt);
            }, Lifestyle.Scoped);

            container.RegisterSingleton <AutoMapper.IMapper>(() =>
            {
                var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();
                cfg.AddProfiles("ParkMark.UI.Web");
                var mapperConfig = new AutoMapper.MapperConfiguration(cfg);
                var rslt         = new AutoMapper.Mapper(mapperConfig);
                return(rslt);
            });
        }
コード例 #28
0
        private static void InitializeContainer(Container container)
        {
            InitializePackages(container);
            container.EnableHttpRequestMessageTracking(GlobalConfiguration.Configuration);
            container.Register <ILoggerFactory, LoggerFactory>(Lifestyle.Scoped);

            container.Register <Logger.ILogRequestContext>(() =>
            {
                var request = container.GetCurrentHttpRequestMessage();
                var rslt    = new Logger.LogRequestContext(request);
                return(rslt);
            }, Lifestyle.Scoped);


            container.Register <IUnitOfWork>(() => new EFUnitOfWorks(Model.API.ConfigValues.EntityFrameworkConntectionString), Lifestyle.Scoped);


            container.Register <IBaseApiControllerDependencies, BaseApiControllerDependencies>(Lifestyle.Scoped);

            container.RegisterConditional(typeof(ILogger),
                                          context =>
            {
                var impType = typeof(Logger.NLogProxy <>).MakeGenericType(context.Consumer.ImplementationType);
                return(impType);
            },
                                          Lifestyle.Scoped, context => true);

            container.RegisterSingleton <AutoMapper.IMapper>(() =>
            {
                var cfg = new AutoMapper.Configuration.MapperConfigurationExpression();
                cfg.AddProfiles("ParkMark.Business");
                var mapperConfig = new AutoMapper.MapperConfiguration(cfg);
                var rslt         = new AutoMapper.Mapper(mapperConfig);
                return(rslt);
            });
        }
コード例 #29
0
 public static void Configure(AutoMapper.IMapper mapper, AutoMapper.Configuration.MapperConfigurationExpression config)
 {
     AutoMapperExtensions.mapper = mapper;
     AutoMapperExtensions.config = config;
 }
コード例 #30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            #region 注入自己的服务
            services.Configure <TokenOptions>(Configuration.GetSection("AuthTokenOptions"));
            services.AddSingleton(typeof(JwtToken));
            services.AddSingleton <IRedisCacheManager, RedisCacheManager>();
            var freeSql = new FreeSql.FreeSqlBuilder()
                          .UseConnectionString(FreeSql.DataType.SqlServer, "server=.;uid=sa;pwd=123456;database=InternalDB")
                          .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
                          .Build();
            var freeSql2 = new FreeSql.FreeSqlBuilder()
                           .UseConnectionString(FreeSql.DataType.SqlServer, "server=192.168.31.138;uid=dev;pwd=dev+-*/86224155;database=YongZhen_GZMModel")
                           .UseMonitorCommand(cmd => Trace.WriteLine(cmd.CommandText))
                           .Build();
            services.AddSingleton(typeof(IFreeSql), freeSql);
            services.AddSingleton(typeof(IFreeSqlFactory), new FreeSqlFactory());
            services.AddScoped(typeof(QiniuService));
            services.AddScoped(typeof(QiniuService));
            #endregion
            #region 配置授权认证
            services
            .AddAuthorization(
                opt =>
            {
                opt.AddPolicy("CustomPermission", ap => ap.AddRequirements(new PermissionRequirement()));
            })
            .AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(option =>
            {
                /***********************************TokenValidationParameters的参数默认值***********************************/
                // RequireSignedTokens = true,
                // SaveSigninToken = false,
                // ValidateActor = false,
                // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
                // ValidateAudience = true,
                // ValidateIssuer = true,
                // ValidateIssuerSigningKey = false,
                // 是否要求Token的Claims中必须包含Expires
                // RequireExpirationTime = true,
                // 允许的服务器时间偏移量
                // ClockSkew = TimeSpan.FromSeconds(300),
                // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                // ValidateLifetime = true
                option.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    ValidAudience            = Configuration.GetSection("AuthTokenOptions:Issuer").Value,
                    ValidIssuer      = Configuration.GetSection("AuthTokenOptions:Audience").Value,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("AuthTokenOptions:Secret").Value)),
                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.FromSeconds(30),
                };
            });
            services.AddSingleton <IAuthorizationHandler, PermissionAuthorizationHandler>();
            #endregion

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(opt =>
            {
                //使用默认方式,不更改元数据的key的大小写
                opt.SerializerSettings.ContractResolver = new DefaultContractResolver();
            });

            #region 注入 HttpContext 服务
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <IAspNetUser, AspNetUser>();
            #endregion

            #region AutoMapper 先注册autoMapper 在使用autofac框架托管
            services.AddAutoMapper(Assembly.Load("Internal.Data"));
            AutoMapper.Configuration.MapperConfigurationExpression expression = new AutoMapper.Configuration.MapperConfigurationExpression();
            expression.AddProfiles(Assembly.Load("Internal.Data"));
            AutoMapper.Mapper.Initialize(expression);

            #endregion

            #region Swagger

            var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1.0.0",
                    Title          = "内部系统 API",
                    Description    = "框架说明文档",
                    TermsOfService = "None",
                    Contact        = new Contact {
                        Name = "Internal.System", Email = "", Url = ""
                    }
                });
                //c.SwaggerDoc("v2", new Info
                //{
                //    Version = "v2.0.0",
                //    Title = "内部系统 API2",
                //    Description = "框架说明文档2",
                //    TermsOfService = "None",
                //    Contact = new Contact { Name = "Internal.System", Email = "", Url = "" }
                //});

                var xmlPath = Path.Combine(basePath, "Internal.App.xml");//这个就是刚刚配置的xml文件名
                if (File.Exists(xmlPath))
                {
                    c.IncludeXmlComments(xmlPath, true);//默认的第二个参数是false,这个是controller的注释,记得修改
                }
                if (File.Exists(xmlPath))
                {
                    c.IncludeXmlComments(Path.Combine(basePath, "Internal.Data.xml"));
                }

                #region Token绑定到ConfigureServices
                //添加header验证信息
                //c.OperationFilter<SwaggerHeader>();
                var security = new Dictionary <string, IEnumerable <string> > {
                    { "Internal.App", new string[] { } },
                };
                c.AddSecurityRequirement(security);
                //方案名称“Blog.Core”可自定义,上下一致即可
                c.AddSecurityDefinition("Internal.App", new ApiKeyScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
                    Name        = "Authorization", //jwt默认的参数名称
                    In          = "header",        //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = "apiKey"
                });
                #endregion
            });
            #endregion
            #region CORS 跨域
            //跨域第二种方法,声明策略,记得下边app中配置
            services.AddCors(c =>
            {
                //↓↓↓↓↓↓↓注意正式环境不要使用这种全开放的处理↓↓↓↓↓↓↓↓↓↓
                c.AddPolicy("AllRequests", policy =>
                {
                    policy
                    .AllowAnyOrigin()    //允许任何源
                    .AllowAnyMethod()    //允许任何方式
                    .AllowAnyHeader()    //允许任何头
                    .AllowCredentials(); //允许cookie
                });
                //↑↑↑↑↑↑↑注意正式环境不要使用这种全开放的处理↑↑↑↑↑↑↑↑↑↑
                List <string> os = new List <string>();
                var origins      = Configuration.GetSection("AllowAnyOrigins");
                if (origins != null)
                {
                    foreach (var cfg in origins.GetChildren())
                    {
                        os.Add($"{cfg.Value}");
                    }
                }
                //一般采用这种方法
                c.AddPolicy("LimitRequests", policy =>
                {
                    policy
                    .WithOrigins(os.ToArray()) //支持多个域名端口,注意端口号后不要带/斜杆:比如localhost:8000/,是错的
                    .AllowAnyHeader()          //Ensures that the policy allows any header.
                    .AllowAnyMethod();
                });
            });

            //跨域 注意下边 Configure方法 中进行配置
            //services.AddCors();
            #endregion

            #region AutoFac

            //实例化 AutoFac  容器
            var builder = new ContainerBuilder();

            //注册要通过反射创建的组件
            //builder.RegisterType<DemandService>().As<IDemandService>();

            var assemblysServices = Assembly.Load("Internal.Service");//要记得!!!这个注入的是实现类层,不是接口层!不是 IServices
            builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces()
            .EnableInterfaceInterceptors()
            .InterceptedBy(typeof(ServiceInterceptorAOP));                            //指定已扫描程序集中的类型注册为提供所有其实现的接口。
            var assemblysRepository = Assembly.Load("Internal.Repository.SqlServer"); //模式是 Load(解决方案名)
            builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces();
            assemblysRepository = Assembly.Load("Internal.Repository.FreeSqlServer"); //模式是 Load(解决方案名)
            builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces();
            assemblysRepository = Assembly.Load("Admin.Service");                     //模式是 Load(解决方案名) FreeSql Service
            builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces().EnableInterfaceInterceptors();

            //  builder.RegisterType<DemandBillOperation>().As<IBillOperation<Demand>>().EnableInterfaceInterceptors();

            //services.AddScoped(typeof(IDemandBillOperation), typeof(DemandBillOperation)).en;

            //将services填充到Autofac容器生成器中
            builder.Populate(services);

            //注册拦截器
            builder.RegisterType <ServiceInterceptorAOP>();

            //使用已进行的组件登记创建新容器
            var ApplicationContainer = builder.Build();

            #endregion

            return(new AutofacServiceProvider(ApplicationContainer));//第三方IOC接管 core内置DI容器
        }