C# ASP.NET核心中应用程序启动逻辑的放置位置
我想用ASP.NET Core 2.1创建一个web服务,它在应用程序启动时检查与数据库的连接是否正常,然后在数据库中准备一些数据 该检查在循环中运行,直到连接成功或用户按Ctrl+C(C# ASP.NET核心中应用程序启动逻辑的放置位置,c#,asp.net-core,.net-core,startup,C#,Asp.net Core,.net Core,Startup,我想用ASP.NET Core 2.1创建一个web服务,它在应用程序启动时检查与数据库的连接是否正常,然后在数据库中准备一些数据 该检查在循环中运行,直到连接成功或用户按Ctrl+C(iaapplicationLifetime)为止。在初始化数据库之前,不要处理任何HTTP调用,这一点很重要。我的问题是:这个代码放在哪里 我需要对依赖项注入系统进行完全初始化,因此我能想到的最早时间是在启动结束时。Configure方法,但是iaapplicationlifetime上的取消令牌似乎在那里不起作
iaapplicationLifetime
)为止。在初始化数据库之前,不要处理任何HTTP调用,这一点很重要。我的问题是:这个代码放在哪里
我需要对依赖项注入系统进行完全初始化,因此我能想到的最早时间是在启动结束时。Configure
方法,但是iaapplicationlifetime
上的取消令牌似乎在那里不起作用(因为asp没有完全启动,所以可以正常使用)
是否有一个可以放置此启动逻辑的官方位置?您可以在
IWebHost
的基础上构建一个扩展方法,该方法允许您在startup.cs
之前运行代码。此外,您可以使用ServiceScopeFactory
初始化您拥有的任何服务(例如DbContext
)
该代码放在哪里
有没有一个官方的地方可以放置这种启动逻辑
Startup.cs是一个很好的开始
Initializer.WaitOnAction(()=> /* ensure db is initialized here */);
/* check https://dotnetfiddle.net/gfTyTL */
我想用ASP.NET Core 2.1创建一个web服务,在应用程序启动时进行检查
namespace MyApp.Services
{
public interface IFileService
{
void CreateDirectoryStructure(string path = "");
void CreateFolder(string name, string path = "");
void CreateFile(string name, string path = "");
bool CheckFileExists(string path);
bool CheckFolderExists(string path);
}
}
例如,我有一个场景要检查文件夹结构,如果不是的话,在应用程序启动后立即创建一个
创建文件夹结构的方法是在FileService.cs中,在任何http请求之前,应用程序启动后,必须通过DI启动该文件夹结构。
appsettings.jsonconatins包含用于创建文件夹结构的结构的键和值
"FolderStructure": {
"Download": {
"English": {
"*": "*"
},
"Hindi": {
"*": "*"
}
},
"Upload": {
"*": "*"
}
}
并在接口和服务下面使用
接口
namespace MyApp.Services
{
public interface IFileService
{
void CreateDirectoryStructure(string path = "");
void CreateFolder(string name, string path = "");
void CreateFile(string name, string path = "");
bool CheckFileExists(string path);
bool CheckFolderExists(string path);
}
}
服务
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Configuration.Binder;
using System.IO;
using Microsoft.Extensions.Logging;
namespace MyApp.Services
{
public class FileService : IFileService
{
private readonly IFileProvider _fileProvider;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IConfiguration _config;
private readonly ILogger<FileService> _logger;
string defaultfolderPath = ConfigurationManager.AppSetting["DefaultDrivePath"];
public FileService(IFileProvider fileProvider, IHostingEnvironment hostingEnvironment, IConfiguration config, ILogger<FileService> logger)
{
_fileProvider = fileProvider;
_hostingEnvironment = hostingEnvironment;
_config = config;
_logger = logger;
}
public void CreateDirectoryStructure(string drivePath = "")
{
if (drivePath.Equals(""))
{
drivePath = ConfigurationManager.AppSetting["DefaultDrivePath"];
_logger.LogInformation($"Default folder path will be picked {drivePath}");
}
foreach (var item in _config.GetSection("FolderStructure").GetChildren())
{
CreateFolder(item.Key, drivePath);
foreach (var i in _config.GetSection(item.Path).GetChildren())
{
if (i.Key != "*")
CreateFolder(i.Key, $"{drivePath}/{item.Key}");
}
}
}
public void CreateFolder(string name, string path = "")
{
string fullPath = string.IsNullOrEmpty(path) ? $"{defaultfolderPath}/{name}" : $"{path}/{name}";
if (!Directory.Exists(fullPath))
{
Directory.CreateDirectory(fullPath);
_logger.LogInformation($"Directory created at {fullPath} on {DateTime.Now}");
}
}
public void CreateFile(string name, string path = "")
{
string fullPath = string.IsNullOrEmpty(path) ? $"{defaultfolderPath}/{name}" : $"{path}/{name}";
if (!File.Exists(fullPath))
{
File.Create(fullPath);
_logger.LogInformation($"File created at {fullPath} on {DateTime.Now}");
}
}
public bool CheckFolderExists(string path)
{
string fullPath = string.IsNullOrEmpty(path) ? defaultfolderPath : path;
return Directory.Exists(fullPath);
}
public bool CheckFileExists(string path)
{
string fullPath = string.IsNullOrEmpty(path) ? defaultfolderPath : path;
return File.Exists(fullPath);
}
}
}
这里您将面临的问题是,您的应用程序在收到HTTP连接之前不会“启动”,因此您的“不处理HTTP调用”的概念是不存在的。它已经在HTTP连接的中间。我建议您或许应该运行windows服务来准备数据库,然后在一切就绪并运行后启用网站。“我想创建一个ASP.NET Core 2.1的Web服务,在应用程序启动时进行检查…”您所指的应用程序是否为Web服务还不完全清楚?尽管这是一个假设。下面介绍了一些实现
IHost
或IHostedService
的选项,例如也有很好的示例
namespace MyApp.Services
{
public interface IFileService
{
void CreateDirectoryStructure(string path = "");
void CreateFolder(string name, string path = "");
void CreateFile(string name, string path = "");
bool CheckFileExists(string path);
bool CheckFolderExists(string path);
}
}
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Configuration.Binder;
using System.IO;
using Microsoft.Extensions.Logging;
namespace MyApp.Services
{
public class FileService : IFileService
{
private readonly IFileProvider _fileProvider;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IConfiguration _config;
private readonly ILogger<FileService> _logger;
string defaultfolderPath = ConfigurationManager.AppSetting["DefaultDrivePath"];
public FileService(IFileProvider fileProvider, IHostingEnvironment hostingEnvironment, IConfiguration config, ILogger<FileService> logger)
{
_fileProvider = fileProvider;
_hostingEnvironment = hostingEnvironment;
_config = config;
_logger = logger;
}
public void CreateDirectoryStructure(string drivePath = "")
{
if (drivePath.Equals(""))
{
drivePath = ConfigurationManager.AppSetting["DefaultDrivePath"];
_logger.LogInformation($"Default folder path will be picked {drivePath}");
}
foreach (var item in _config.GetSection("FolderStructure").GetChildren())
{
CreateFolder(item.Key, drivePath);
foreach (var i in _config.GetSection(item.Path).GetChildren())
{
if (i.Key != "*")
CreateFolder(i.Key, $"{drivePath}/{item.Key}");
}
}
}
public void CreateFolder(string name, string path = "")
{
string fullPath = string.IsNullOrEmpty(path) ? $"{defaultfolderPath}/{name}" : $"{path}/{name}";
if (!Directory.Exists(fullPath))
{
Directory.CreateDirectory(fullPath);
_logger.LogInformation($"Directory created at {fullPath} on {DateTime.Now}");
}
}
public void CreateFile(string name, string path = "")
{
string fullPath = string.IsNullOrEmpty(path) ? $"{defaultfolderPath}/{name}" : $"{path}/{name}";
if (!File.Exists(fullPath))
{
File.Create(fullPath);
_logger.LogInformation($"File created at {fullPath} on {DateTime.Now}");
}
}
public bool CheckFolderExists(string path)
{
string fullPath = string.IsNullOrEmpty(path) ? defaultfolderPath : path;
return Directory.Exists(fullPath);
}
public bool CheckFileExists(string path)
{
string fullPath = string.IsNullOrEmpty(path) ? defaultfolderPath : path;
return File.Exists(fullPath);
}
}
}
services.AddSingleton<IFileService, FileService>();
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IFileService FileService)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
//dont change the below order as middleware exception need to be registered before UseMvc method register
app.ConfigureCustomMiddleware();
// app.UseHttpsRedirection();
app.UseMvc();
FileService.CreateDirectoryStructure();
}