using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; 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 Haoliang.Core.Services; using Haoliang.Api.Middleware; namespace Haoliang.Api { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "CNC Data Collection API", Version = "v1" }); }); // 配置跨域 services.AddCors(options => { options.AddPolicy("AllowAll", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); // 配置SignalR services.AddSignalR(); // 配置服务依赖注入 ConfigureServices(services); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CNC Data Collection API v1")); } // 中间件顺序很重要 app.UseMiddleware(); app.UseMiddleware(); app.UseMiddleware(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub("/realtime"); }); } private void ConfigureServices(IServiceCollection services) { // 配置数据库连接 var connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext(options => options.UseSqlServer(connectionString)); // 配置内存缓存 services.AddMemoryCache(); services.AddDistributedMemoryCache(); // 注册缓存服务 services.AddSingleton(); // 注册状态机服务 services.AddHostedService(); // 注册服务 services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); // 注册配置服务 services.AddScoped(); // 注册仓储 services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); // 注册SignalR Hub services.AddSingleton(); } } }