参考来源 https://www.jb51.net/article/265865.htm
首先要 指定配置文件,否则运行的时候找不到appsettings.json ,
在使用 sc create 创建 Windows 服务时,确实存在一个问题,即服务的默认工作目录是 C:\Windows\System32,而不是服务的可执行文件所在的目录。这就是为什么你的服务找不到 appsettings.json 文件的原因。
然后要安装 依赖 Microsoft.Extensions.Hosting.WindowsServices包
示例代码如下
using System.Diagnostics;
using System.Reflection;
using System.Text.Json.Serialization;
using ApiHelper.ext;
using ApiHelper.middleware;
using Microsoft.EntityFrameworkCore;
using pointserver.api;
using pointserver.dbcontext;
using pointserver.impl;
using pointserver.lifecycle;
using TDEngineHelper;
var assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
var scCMD = $"sc create {assemblyName} binpath= \"{Process.GetCurrentProcess().MainModule!.FileName}\" start= auto";
Console.WriteLine($"创建服务语句为 {scCMD}");
var builder = WebApplication.CreateBuilder(args);
IConfiguration configuration = null; //so it can be used on other configuration functions bellow
var baseDirectory = AppContext.BaseDirectory;
//load config file, build it, give it to WebApplication and keep the config variable for further use.
// 必须指定配置文件,否则做成服务 读取不到配置文件
builder.WebHost.ConfigureAppConfiguration(
(hostingContext, config) =>
{
var path = Path.Combine(baseDirectory,builder.Environment.IsDevelopment()?"appsettings.Development.json"
: "appsettings.json");
config.AddJsonFile(path, optional: false, reloadOnChange: true);
config.AddEnvironmentVariables();
configuration = config.Build();
});
Console.WriteLine($"当前工作目录为 {baseDirectory}, 将其设置为配置文件目录");
builder.Configuration.SetBasePath(baseDirectory); // 设置配置文件路径 不加这行,sc 创建服务 默认工作目录是 C:\Windows\System32 会找不到配置文件
builder.UseLog();
var mysqlConnectionString = builder.Configuration["ConnectionStrings:MySQL"];
Console.WriteLine($"mysql 连接字符串为 {mysqlConnectionString}");
var tdEngineHost = builder.Configuration.GetConnectionString("TDEngineHost");
var tdEnginePort = builder.Configuration.GetConnectionString("TDEnginePort");
var tdEngineUser = builder.Configuration.GetConnectionString("TDEngineUser");
var tdEnginePass = builder.Configuration.GetConnectionString("TDEnginePassword");
var tdEngineDb = builder.Configuration.GetConnectionString("TDEngineDatabase");
// port to short
short.TryParse(tdEnginePort, out var tdEnginePortShort);
// Add services to the container.
builder.Services.AddControllers()
.AddJsonOptions(x => x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles); // 防止Json 循环引用
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IPointRepo, PointRepo>();
builder.Services.AddScoped<IPointGroupRepo, PointGroupRepo>();
builder.Services.AddScoped<IPointGroupRltPointRepo, PointGroupRltPointRepo>();
builder.Services.AddScoped<IUnitRepo, UnitRepo>();
builder.Services.AddScoped<ISystemRepo, SystemRepo>();
builder.Services.AddSingleton<IHostedService, HostService>(); // 程序启停服务
// tdEngine service 依赖注入
builder.Services.AddSingleton<ITDEngineRepo>(new TDEngineRepo(tdEngineHost, tdEngineUser, tdEnginePass, tdEngineDb,
tdEnginePortShort));
builder.Services.AddDbContext<PointServerDbContext>();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddWindowsService(o => { o.ServiceName = assemblyName; }); // 必须加上这个,不然报错 windows 无法启动pointsrever 服务 错误 1053 : 服务没有及时响应启动或控制请求
var app = builder.Build();
app.UseCustomExceptionHandler(); // 异常中间件
app.UseSwagger();
app.UseSwaggerUI();
// 允许所有跨域
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials());
app.UseStaticFiles();
app.MapControllers();
app.Run();
标签:core,windows,builder,Services,var,using,net,Configuration,app
From: https://www.cnblogs.com/ifnk/p/17782324.html