// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. //关闭GDPR规范,解决存不进Cookie的问题 options.CheckConsentNeeded = context => false; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc(option => { option.ModelBinderProviders.Insert(0, new JsonBinderProvider()); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMemoryCache(); services.AddOptions(); services.AddRouting(options => options.LowercaseUrls = false); //添加对AutoMapper的支持,参考https://www.cnblogs.com/skyfreedom/p/11073114.html services.AddAutoMapper(typeof(AutoMapperProfile)); //映射配置文件 services.Configure <AppSetting>(Configuration.GetSection("AppSetting")); services.AddDbContext <OpenAuthDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("OpenAuthDBContext"), b => b.UseRowNumberForPaging())); //使用AutoFac进行注入 return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddOptions(); services.Configure <SiteConfig>(Configuration.GetSection("SiteConfig")); services.AddLogging(); services.AddResponseCompression(); services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>()); services.AddMvc(); GlobalStateHandlers.Handlers.Add(new SucceededStateExpireHandler(int.Parse(Configuration["Hangfire:JobExpirationTimeout"]))); services.AddHangfire(x => { var connectionString = Configuration["Data:Redis:ConnectionString"]; x.UseRedisStorage(connectionString, new RedisStorageOptions() { //活动服务器超时时间 InvisibilityTimeout = TimeSpan.FromMinutes(60), Db = int.Parse(Configuration["Data:Redis:Db"]) }); x.UseDashboardMetric(DashboardMetrics.ServerCount) .UseDashboardMetric(DashboardMetrics.RecurringJobCount) .UseDashboardMetric(DashboardMetrics.RetriesCount) .UseDashboardMetric(DashboardMetrics.AwaitingCount) .UseDashboardMetric(DashboardMetrics.EnqueuedAndQueueCount) .UseDashboardMetric(DashboardMetrics.ScheduledCount) .UseDashboardMetric(DashboardMetrics.ProcessingCount) .UseDashboardMetric(DashboardMetrics.SucceededCount) .UseDashboardMetric(DashboardMetrics.FailedCount) .UseDashboardMetric(DashboardMetrics.DeletedCount); }); services.AddDbContext <EFCoreDBContext>(options => options.UseMySql(Configuration["Data:MyCat:ConnectionString"])); var container = AutofacExt.InitAutofac(services, Assembly.GetExecutingAssembly()); return(new AutofacServiceProvider(container)); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //services.AddIdentity<ApplicationUser, Role>().AddUserStore<CustomUserStore>() // .AddDefaultTokenProviders(); //services.AddTransient<IRoleStore<Role>, CustomRoleStore>(); var builder = services.AddIdentityServer() .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiResources(Config.GetApis()) .AddInMemoryClients(Config.GetClients(Configuration["IdentityUrl"])) //Environment.IsProduction() .AddProfileService <CustomProfileService>(); services.AddCors(); //全部用测试环境,正式环境请参考https://www.cnblogs.com/guolianyu/p/9872661.html //if (Environment.IsDevelopment()) //{ builder.AddDeveloperSigningCredential(); //} //else //{ // throw new Exception("need to configure key material"); //} services.AddMvc().AddControllersAsServices().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMemoryCache(); services.AddCors(); services.AddDbContext <EFCoreDBContext>(options => options.UseMySql(Configuration["Data:MyCat:ConnectionString"])); return(new AutofacServiceProvider(AutofacExt.InitAutofac(services, Assembly.GetExecutingAssembly()))); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "expense_manage WebApi", Version = "v1", Description = "by ycyreddevil" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); options.IncludeXmlComments(xmlPath); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }); services.AddMvc(); services.AddCors(); services.AddDbContext <yuyuDBContext>(options => options.UseMySql(Configuration.GetConnectionString("yuyuDBContext"))); return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "project_manage WebApi", Version = "v1", Description = "by ycyreddevil" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); options.IncludeXmlComments(xmlPath); options.OperationFilter <GlobalHttpHeaderOperationFilter>(); // 添加httpHeader参数 }); services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new SystemTextJsonConvert.DateTimeConverter()); options.JsonSerializerOptions.Converters.Add(new SystemTextJsonConvert.DateTimeConverter()); }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddMvc(options => options.EnableEndpointRouting = false); services.AddMvc(config => { config.Filters.Add <LoginFilter>(); }).AddControllersAsServices(); services.AddCors(); return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
// This method gets called by the runtime. Use this method to add services to the container.IServiceProvider public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. //关闭GDPR规范 options.CheckConsentNeeded = context => false; options.MinimumSameSitePolicy = SameSiteMode.None; }); // services.AddDbContext<Data.EntityFramework.MyDbContext>(options=>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b=>b.MigrationsAssembly("Com.App.Web"))); services.AddDbContext <Data.EntityFramework.MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), c => c.UseRowNumberForPaging())); // services.AddDbContext<Data.EntityFramework.EfDbContext>(options => // options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Com.App.Web"))); //依赖注入 //DIBllRegister bllRegister = new DIBllRegister(); // bllRegister.DIRegister(services); services.AddMemoryCache(); services.Configure <IISOptions>(option => { }); services.AddSession(); //登录拦截服务 services.AddScoped <LoginActionFilter>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //使用AutoFac进行注入 return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. //关闭GDPR规范 options.CheckConsentNeeded = context => false; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc(option => { option.ModelBinderProviders.Insert(0, new JsonBinderProvider()); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMemoryCache(); services.AddOptions(); services.AddDbContext <XgossContext>(options => options.UseSqlServer(Configuration.GetConnectionString("XgossContext"))); //映射配置文件 services.Configure <AppSetting>(Configuration.GetSection("AppSetting")); //添加Session相关 services.AddDistributedMemoryCache(); services.AddSession(); //使用AutoFac进行注入 return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
protected void Application_Start() { AutofacExt.InitAutofac(); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); }
protected void Application_Start() { AutofacExt.InitAutofac(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
protected void Application_Start() { AutofacExt.InitAutofac(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ModelBinders.Binders.Add(typeof(JObject), new JobjectModelBinder()); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc(); var sqlConnectionString = Configuration.GetConnectionString("Default"); //添加数据上下文 services.AddDbContext <HLDBContext>(options => options.UseSqlServer(sqlConnectionString)); return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
public void Init() { var serviceCollection = GetService(); serviceCollection.AddMemoryCache(); serviceCollection.AddOptions(); var container = AutofacExt.InitAutofac(serviceCollection); _autofacServiceProvider = new AutofacServiceProvider(container); }
public void Init() { var serviceCollection = GetService(); serviceCollection.AddMemoryCache(); serviceCollection.AddOptions(); serviceCollection.AddDbContext <XgossContext>(options => options.UseSqlServer("Data Source=117.27.89.185,60012;Database=xgoss_netcore;Uid=sa;Pwd=Dongri_123456")); var container = AutofacExt.InitAutofac(serviceCollection); _autofacServiceProvider = new AutofacServiceProvider(container); }
public void Init() { var serviceCollection = GetService(); serviceCollection.AddMemoryCache(); serviceCollection.AddOptions(); serviceCollection.AddDbContext <OpenAuthDBContext>(options => options.UseSqlServer("Data Source=.;Initial Catalog=OpenAuthDB;User=sa;Password=000000;Integrated Security=True")); var container = AutofacExt.InitAutofac(serviceCollection); _autofacServiceProvider = new AutofacServiceProvider(container); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(); services.AddSession(options => { options.Cookie.HttpOnly = true; }); services.AddMemoryCache(); services.AddOptions(); services.Configure <SiteConfig>(Configuration.GetSection("SiteConfig")); services.AddLogging(); services.AddCloudscribePagination(); services.AddResponseCompression(); services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>()); services.AddMiniProfiler().AddEntityFramework(); services.AddMvc(cfg => { cfg.Filters.Add(typeof(ExceptionAttribute));//异常捕获 }); services.AddMvc(cfg => { cfg.Filters.Add(typeof(MvcMenuFilter)); }); services.AddHangfire(x => { var connectionString = Configuration["Data:Redis:ConnectionString"]; x.UseRedisStorage(connectionString, new Hangfire.Redis.RedisStorageOptions() { Db = 10 }); }); #region mysql ////services.AddHangfire(x => x.UseStorage(new MySqlStorage(Configuration["Hangfire:ConStr"] //// , //// new MySqlStorageOptions //// { //// QueuePollInterval = TimeSpan.FromSeconds(600) //- 作业队列轮询间隔。默认值为15秒。 //// } //// ))); #endregion services.AddDbContext <EFCoreDBContext>(options => options.UseMySql(Configuration["Data:MyCat:ConnectionString"])); return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //services.AddIdentity<ApplicationUser, Role>().AddUserStore<CustomUserStore>() // .AddDefaultTokenProviders(); //services.AddTransient<IRoleStore<Role>, CustomRoleStore>(); var builder = services.AddIdentityServer() .AddInMemoryIdentityResources(Config.GetIdentityResources()) .AddInMemoryApiResources(Config.GetApis()) .AddInMemoryClients(Config.GetClients(Environment.IsProduction())) .AddProfileService <CustomProfileService>(); services.AddCors(); //全部用测试环境,正式环境请参考https://www.cnblogs.com/guolianyu/p/9872661.html //if (Environment.IsDevelopment()) //{ builder.AddDeveloperSigningCredential(); //} //else //{ // throw new Exception("need to configure key material"); //} services.Configure <AppSetting>(Configuration.GetSection("AppSetting")); services.AddMvc().AddControllersAsServices().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMemoryCache(); services.AddCors(); //在startup里面只能通过这种方式获取到appsettings里面的值,不能用IOptions😰 var dbType = ((ConfigurationSection)Configuration.GetSection("AppSetting:DbType")).Value; if (dbType == Define.DBTYPE_SQLSERVER) { services.AddDbContext <OpenAuthDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("OpenAuthDBContext"))); } else //mysql { services.AddDbContext <OpenAuthDBContext>(options => options.UseMySql(Configuration.GetConnectionString("OpenAuthDBContext"))); } return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
public void Init() { var serviceCollection = GetService(); serviceCollection.AddMemoryCache(); serviceCollection.AddOptions(); // 测试my sql // serviceCollection.AddDbContext<OpenAuthDBContext>(options => // options.UseMySql("server=127.0.0.1;user id=root;database=openauthdb;password=000000")); serviceCollection.AddDbContext <yfjbContext>(options => options.UseSqlServer("Data Source=.;Initial Catalog=OpenAuthDB;User=sa;Password=000000;Integrated Security=True")); var container = AutofacExt.InitAutofac(serviceCollection); _autofacServiceProvider = new AutofacServiceProvider(container); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Application_Start(object sender, EventArgs e) { // DbInitService.Init(); AutoMapperConfiguration.ConfigExt(); AutofacExt.InitAutofac(); // Log.Info("log", "Application_Start:" + DateTime.Now.ToString()); // 在应用程序启动时运行的代码 AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteTable.Routes.Ignore(""); //Allow index.html to load RouteConfig.RegisterRoutes(RouteTable.Routes); //取消注释默认返回 json GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); JobManager.Initialize(new TaskTime()); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => false;//为 True 时获取不到 Session 的值 options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDistributedMemoryCache(); //添加Session 服务 services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(60); options.Cookie.HttpOnly = true; }); services.AddHttpContextHelperAccessor(); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddJsonOptions(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //不使用驼峰样式的key options.SerializerSettings.ContractResolver = new DefaultContractResolver(); //设置时间格式 //options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }); //设置认证cookie名称、过期时间、是否允许客户端读取 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = "nkblog"; //cookie名称 options.Cookie.Expiration = TimeSpan.FromHours(1); //过期时间 options.Cookie.HttpOnly = true; //不允许客户端获取 options.SlidingExpiration = true; // 是否在过期时间过半的时候,自动延期 }); //Redis.Initialization(); return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //启用MemoryCache services.AddMemoryCache(); //设置MemoryCache缓存有效时间为5分钟。 services.Configure <MemoryCacheEntryOptions>( options => options.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)); //跨域 services.AddCors(); //配置DBConctext services.AddDbContext <VDbContext>(options => { options.EnableSensitiveDataLogging(true); options.UseSqlServer(Configuration.GetConnectionString("VDbContext")); }); //记录日志 services.AddMvc(option => { option.Filters.Add(new GlobalExceptionFilter()); }) .AddControllersAsServices(); return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddOptions(); services.Configure <SiteConfig>(Configuration.GetSection("SiteConfig")); services.AddLogging(); services.AddResponseCompression(); services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>()); services.AddHangfire(x => { var connectionString = Configuration["Data:Redis:ConnectionString"]; x.UseRedisStorage(connectionString, new RedisStorageOptions() { Db = int.Parse(Configuration["Data:Redis:Db"]) }); }); #region mysql //services.AddHangfire(x => x.UseStorage(new MySqlStorage( // Configuration["Hangfire:ConStr"], // new MySqlStorageOptions // { // TransactionIsolationLevel = IsolationLevel.ReadCommitted, // 事务隔离级别。默认是读取已提交。 // QueuePollInterval = TimeSpan.FromSeconds(15), //- 作业队列轮询间隔。默认值为15秒。 // JobExpirationCheckInterval = TimeSpan.FromHours(1), //- 作业到期检查间隔(管理过期记录)。默认值为1小时。 // CountersAggregateInterval = TimeSpan.FromMinutes(5), //- 聚合计数器的间隔。默认为5分钟。 // PrepareSchemaIfNecessary = true, //- 如果设置为true,则创建数据库表。默认是true。 // DashboardJobListLimit = 50000, //- 仪表板作业列表限制。默认值为50000。 // TransactionTimeout = TimeSpan.FromMinutes(1), //- 交易超时。默认为1分钟。 // TablePrefix = "Hangfire" //- 数据库中表的前缀。默认为none // } // ))); #endregion services.AddDbContext <EFCoreDBContext>(options => options.UseMySql(Configuration["Data:MyCat:ConnectionString"])); var container = AutofacExt.InitAutofac(services); // GlobalConfiguration.Configuration.UseAutofacActivator(container); return(new AutofacServiceProvider(container)); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(option => { option.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Version = "v1", Title = " SharePlatform.WebApi", Description = "by SharePlatform" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); option.IncludeXmlComments(xmlPath); option.OperationFilter <GlobalHttpHeaderOperationFilter>(); // 添加httpHeader参数 }); services.AddMvc().AddControllersAsServices().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMemoryCache(); services.AddCors(); //在startup里面只能通过这种方式获取到appsettings里面的值,不能用IOptions😰 var dbType = ((ConfigurationSection)Configuration.GetSection("AppSetting:DbType")).Value; if (dbType == Define.DBTYPE_SQLSERVER) { services.AddDbContext <SharePlatformDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SharePlatformDBContext"))); } else //mysql { services.AddDbContext <SharePlatformDBContext>(options => options.UseMySql(Configuration.GetConnectionString("SharePlatformDBContext"))); } return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { var connStr = Configuration.GetConnectionString("MySqlConn"); var assemblyName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDbContext <LBDDBContext>(option => { option.UseMySql(connStr, b => b.MigrationsAssembly(assemblyName)); }); services.AddMvc(option => { option.Filters.Add <AuthFilter>(); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2); return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
public void ConfigureContainer(ContainerBuilder builder) { AutofacExt.InitAutofac(builder); }
public IServiceProvider ConfigureServices(IServiceCollection services) { if (bool.Parse(Configuration["IsIdentity"])) { System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddAuthentication(options => { options.DefaultScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("Cookies") .AddOpenIdConnect("oidc", options => { options.Authority = Configuration["IdentityUrl"]; options.RequireHttpsMetadata = false; options.ClientId = "CompanyName.ProjectName.Mvc"; options.SaveTokens = true; options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name", RoleClaimType = "role", }; }); } else { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(); } services.AddSession(options => { options.Cookie.HttpOnly = true; }); services.AddMemoryCache(); services.AddOptions(); services.Configure <SiteConfig>(Configuration.GetSection("SiteConfig")); services.AddLogging(); services.AddCloudscribePagination(); services.AddResponseCompression(); services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>()); if (bool.Parse(Configuration["IsUseMiniProfiler"])) { services.AddMiniProfiler().AddEntityFramework(); } services.AddMvc(cfg => { cfg.Filters.Add(typeof(ExceptionAttribute));//异常捕获 }); services.AddMvc(cfg => { cfg.Filters.Add(typeof(MvcMenuFilter)); }); services.AddHangfire(x => { var connectionString = Configuration["Data:Redis:ConnectionString"]; x.UseRedisStorage(connectionString, new Hangfire.Redis.RedisStorageOptions() { Db = int.Parse(Configuration["Data:Redis:Db"]) }); }); services.AddDbContext <EFCoreDBContext>(options => options.UseMySql(Configuration["Data:MyCat:ConnectionString"])); return(new AutofacServiceProvider(AutofacExt.InitAutofac(services, Assembly.GetExecutingAssembly()))); }
protected void Application_Start() { AutofacExt.InitAutofac(); GlobalConfiguration.Configure(WebApiConfig.Register); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure <FormOptions>(options => { options.ValueCountLimit = int.MaxValue; options.ValueLengthLimit = int.MaxValue; options.KeyLengthLimit = int.MaxValue; options.MultipartBodyLengthLimit = int.MaxValue; options.MultipartBoundaryLengthLimit = int.MaxValue; }); services.AddMvc(option => { option.ModelBinderProviders.Insert(0, new JsonBinderProvider()); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMemoryCache(); services.AddOptions(); //映射配置文件 services.Configure <AppSetting>(Configuration.GetSection("AppSetting")); //解密数据库连接字符串的密码 SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("BaseDBContext")); sqlConnectionStringBuilder.Password = Encryption.Decrypt(sqlConnectionStringBuilder.Password); services.AddDbContext <BaseDBContext>(options => //SQL2008启用分页支持 options.UseSqlServer(sqlConnectionStringBuilder.ConnectionString, b => b.UseRowNumberForPaging()) ); #region 启用Quartz中间件 services.AddQuartz(options => { options.UseSqlServer(sqlConnectionStringBuilder.ConnectionString); options.UseProperties(false); }); #endregion //注册数据库基础操作和工作单元 services.AddScoped(typeof(IRepository <>), typeof(Repository <>)); services.AddScoped(typeof(IUnitWork), typeof(UnitWork)); services.AddScoped(typeof(ISqlWork), typeof(SqlWork)); #region 添加Swagger中间件 services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Version = "v1", Title = "华恒API", Description = "华恒API接口", }); //注入WebAPI注释文件给Swagger var xmlPath = Path.Combine(AppContext.BaseDirectory, "WebMvc.xml"); options.IncludeXmlComments(xmlPath, true); var assembly = Assembly.GetAssembly(typeof(BaseDBContext)); options.IncludeXmlComments(assembly.Location.Replace("dll", "xml")); options.IgnoreObsoleteActions(); }); #endregion services.AddSignalR(); //使用AutoFac进行注入 return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { //swagger services.AddSwaggerGen(option => { option.SwaggerDoc("v1", new Info { Title = "Gzh.Template.Core.WebApi", Version = "v1" }); option.SwaggerDoc("v2", new Info { Title = "Gzh.Template.Core.WebApi2", Version = "v2" }); option.DocInclusionPredicate((docName, apiDesc) => { if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo)) { return(false); } var versions = methodInfo.DeclaringType .GetCustomAttributes(true) .OfType <ApiExplorerSettingsAttribute>() .Select(attr => attr.GroupName); if (docName.ToLower() == "v1" && versions.FirstOrDefault() == null) { return(true);//无ApiExplorerSettings的将在v1中显示 } return(versions.Any(v => v.ToString() == docName)); }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); option.IncludeXmlComments(xmlPath); }); //mysql string connectionString = Configuration.GetConnectionString("MysqlConnectionString"); services.AddDbContext <MysqlContext>(options => options.UseMySQL(connectionString)); //mongodb services.Configure <DBSettings>( options => { options.ConnectionString = Configuration.GetSection("MongoDb:ConnectionString").Value; options.Database = Configuration.GetSection("MongoDb:Database").Value; }); services.AddSingleton <ISchedulerFactory, StdSchedulerFactory>();//注册ISchedulerFactory的实例。 //跨域 services.AddCors(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddTransient <HelloJob>(); // 这里使用瞬时依赖注入 services.AddTransient <HelloJobTest>(); services.AddSingleton <QuartzStartup>(); //Autofac return(new AutofacServiceProvider(AutofacExt.InitAutofac(services))); }
/// <summary> /// /// </summary> /// <param name="services"></param> // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>()); services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; options.SerializerSettings.Converters.Add( new Newtonsoft.Json.Converters.IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" } ); //小写 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.SerializerSettings.ContractResolver = new DefaultContractResolver(); // // options.SerializerSettings.DateFormatString = "yyyy-MM-dd"; }); // services.AddMvc().AddXmlSerializerFormatters(); // services.AddMvc().AddXmlDataContractSerializerFormatters(); services.AddLogging(); services.AddCors(options => options.AddPolicy("AllowSameDomain", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader() )); services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSameDomain")); }); #region Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "接口文档", Description = "接口文档-基础", TermsOfService = "https://example.com/terms", Contact = new Contact { Name = "XXX1111", Email = "*****@*****.**", Url = "https://example.com/terms" } , License = new License { Name = "Use under LICX", Url = "https://example.com/license", } }); c.SwaggerDoc("v2", new Info { Version = "v2", Title = "接口文档", Description = "接口文档-基础", TermsOfService = "https://example.com/terms", Contact = new Contact { Name = "XXX2222", Email = "*****@*****.**", Url = "https://example.com/terms" } , License = new License { Name = "Use under LICX", Url = "https://example.com/license", } }); c.OperationFilter <HttpHeaderOperationFilter>(); c.DocumentFilter <HiddenApiFilter>(); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"CompanyName.ProjectName.ICommonServer.xml")); }); #endregion Swagger #region MiniProfiler if (bool.Parse(Configuration["IsUseMiniProfiler"])) { //https://www.cnblogs.com/lwqlun/p/10222505.html services.AddMiniProfiler(options => options.RouteBasePath = "/profiler" ).AddEntityFramework(); } #endregion MiniProfiler services.AddDbContext <EFCoreDBContext>(options => options.UseMySql(Configuration["Data:MyCat:ConnectionString"])); var container = AutofacExt.InitAutofac(services, Assembly.GetExecutingAssembly()); return(new AutofacServiceProvider(container)); }