Startup.cs 9.08 KB
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using Autofac.Extensions.DependencyInjection;
using Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Microsoft.Extensions.Hosting;
using Quartz.Spi;
using Swashbuckle.AspNetCore.Swagger;
using WebApp;
using WebRepository;
using Quartz.Impl;
using MySqlConnector;
using Microsoft.Extensions.Options;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.FileIO;

namespace WebMvc
{
    public class Startup
    {
        private IScheduler _sched;
        private IUnitWork _unitWork;

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

        public IConfiguration Configuration { get; }

        // 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;
            });
            // 注册默认的 ISchedulerFactory 并使用它来获取调度器
            services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
            services.AddSingleton<IScheduler>(provider =>
            {
                var schedulerFactory = provider.GetRequiredService<ISchedulerFactory>();
                return schedulerFactory.GetScheduler().GetAwaiter().GetResult();
            });


            _ = services.AddControllersWithViews(options =>
            {
                options.EnableEndpointRouting = false;
                options.ModelBinderProviders.Insert(0, new JsonBinderProvider());
            })
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
                        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

            services.AddMemoryCache();
            services.AddOptions();


            services.Configure<AppSetting>(Configuration.GetSection("AppSetting"));

            #region 数据库配置

            var baseDbDbType = Configuration.GetSection("DbType")?["BaseDbContext"];
            var acsDbDbType = Configuration.GetSection("DbType")?["ACSDbContext"];

            //WEB
            if (baseDbDbType == "MSSQL")
            {
                SqlConnectionStringBuilder BaseDbBuilder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("BaseDbContext"));
                BaseDbBuilder.Password = BaseDbBuilder.Password.EndsWith("==") ? Encryption.Decrypt(BaseDbBuilder.Password) : BaseDbBuilder.Password;

                services.AddDbContext<BaseDbContext>(options =>
                    options.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole()))
                     .UseSqlServer(BaseDbBuilder.ConnectionString)
                );
                var option = new DbContextOptionsBuilder<BaseDbContext>()
                    .UseMySql(BaseDbBuilder.ConnectionString, new MySqlServerVersion(new Version(5, 7, 43)))
                    .Options;
                services.AddScoped<IUnitWork>(x => new UnitWork(new BaseDbContext(option)));
            }
            else if (baseDbDbType == "MYSQL")
            {
                MySqlConnectionStringBuilder BaseDbBuilder = new MySqlConnectionStringBuilder(Configuration.GetConnectionString("BaseDbContext"));
                BaseDbBuilder.Password = BaseDbBuilder.Password.EndsWith("==") ? Encryption.Decrypt(BaseDbBuilder.Password) : BaseDbBuilder.Password;
                services.AddDbContext<BaseDbContext>(option =>
                {
                    option.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole()));
                    option.UseMySql(BaseDbBuilder.ConnectionString, new MySqlServerVersion(new Version(5, 7, 43)));
                }, ServiceLifetime.Transient);
                //var option = new DbContextOptionsBuilder<BaseDbContext>()
                //    .UseMySql(BaseDbBuilder.ConnectionString, new MySqlServerVersion(new Version(5, 7, 43)))
                //    .Options;
                ////services.AddTransient<IUnitWork>(x => new UnitWork(new BaseDbContext(option)));
                //services.AddTransient<DbContext>(provider => new BaseDbContext(option));
                services.AddTransient<IUnitWork, UnitWork>();
            }
            else
            {
                Console.WriteLine($"BaseDbContext对应的数据类型{baseDbDbType}未实现");
            }
            //RCS 
            if (acsDbDbType == "MSSQL")
            {
                SqlConnectionStringBuilder ACSDbBuilder = new SqlConnectionStringBuilder(Configuration.GetConnectionString("ACSDbContext"));
                ACSDbBuilder.Password = ACSDbBuilder.Password.EndsWith("==") ? Encryption.Decrypt(ACSDbBuilder.Password) : ACSDbBuilder.Password;

                services.AddDbContext<ACSDbContext>(options =>
                    options.UseSqlServer(ACSDbBuilder.ConnectionString), ServiceLifetime.Scoped
                );
            }
            else if (acsDbDbType == "MYSQL")
            {
                MySqlConnectionStringBuilder ACSDbBuilder = new MySqlConnectionStringBuilder(Configuration.GetConnectionString("ACSDbContext"));
                ACSDbBuilder.Password = ACSDbBuilder.Password.EndsWith("==") ? Encryption.Decrypt(ACSDbBuilder.Password) : ACSDbBuilder.Password;

                services.AddDbContext<ACSDbContext>(option =>
                {
                    option.UseMySql(ACSDbBuilder.ConnectionString, new MySqlServerVersion(new Version(5, 7, 43)));
                }, ServiceLifetime.Transient);
            }
            else
            {
                Console.WriteLine($"ACSDbContext对应的数据类型{baseDbDbType}未实现");
            }

            //����Quartz��
            //services.AddQuartz(options =>
            //{

            //    options.UseInMemoryStore();
            //});
            #endregion


            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
            services.AddScoped(typeof(IRepositoryAcs<>), typeof(RepositoryAcs<>));
            // services.AddScoped(typeof(IUnitWork), typeof(UnitWork));
            services.AddScoped(typeof(IUnitWorkAcs), typeof(UnitWorkAcs));

            #region Swagger 配置
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    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();


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

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

            _sched = sched;
            _unitWork = unitWork;

            app.UseStaticFiles();

            #region Swagger
            //app.UseSwagger();
            //app.UseSwaggerUI(c =>
            //{
            //    c.ShowExtensions();
            //    c.SwaggerEndpoint("/swagger/v1/swagger.json", "����API�ӿ��ĵ�");
            //    c.InjectStylesheet("/css/swagger.css");
            //    c.DisplayOperationId();
            //    c.DisplayRequestDuration();
            //    c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.List);
            //});
            #endregion

            #region  Quartz 定时器


            var sysJobList = _unitWork.Find<SysJob>(u => u.Status.Equals("0"));
            foreach (var item in sysJobList)
            {
                JobApp.AddJob(_sched, item);
            }
            #endregion

            app.UseMvcWithDefaultRoute();

            _ = app.UseMvc(routes =>
            {
                routes.MapRoute(
                  name: "areas",
                  template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                );
            });
        }
    }
}