c# - 在 ASP.NET Core 中全局重用变量
问题描述
我必须强制这些变量在我想使用的每个变量上重用,这让我很难。我需要创建一个类来定义这些变量并在整个程序中使用它们。我怎样才能做到这一点?
string RootFolderName = "Uplaod";
string ProductPictureFolder = "ProductPictureFolder";
string ProductMainPictureFolder = "ProductMainPicture";
string WebRootPath = _hostingEnvironment.WebRootPath;
string RootPath = Path.Combine(WebRootPath, RootFolderName);
string ProductPicturePath = Path.Combine(WebRootPath, RootFolderName, ProductPictureFolder);
string ProductMainPicturePath = Path.Combine(WebRootPath, RootFolderName, ProductPictureFolder, ProductMainPictureFolder);
string newPath = Path.Combine(WebRootPath, ProductMainPicturePath);
解决方案
您可以使用单例类,这里是:
界面:
public interface IApplicationData
{
string RootFolderName { get; }
string ProductPictureFolder { get; }
string ProductMainPictureFolder { get; }
string WebRootPath { get; }
string RootPath { get; }
string GetProductPicturePath();
string GetProductMainPicturePath();
string GetNewPath();
}
具体实施:
public class ApplicationData : IApplicationData
{
readonly IHostingEnvironment _hostingEnvironment;
public ApplicationData(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public string RootFolderName => "Upload";
public string ProductPictureFolder => "ProductPictureFolder";
public string ProductMainPictureFolder => "ProductMainPicture";
public string WebRootPath => _hostingEnvironment.WebRootPath;
public string RootPath => Path.Combine(WebRootPath, RootFolderName);
public string GetProductPicturePath()
{
return Path.Combine(WebRootPath, RootFolderName, ProductPictureFolder);
}
public string GetProductMainPicturePath()
{
string path = Path.Combine(WebRootPath, RootFolderName, ProductPictureFolder, ProductMainPictureFolder);
return path;
}
public string GetNewPath()
{
string productMainPicturePath = GetProductMainPicturePath();
return Path.Combine(WebRootPath, productMainPicturePath);
}
}
在 DI Container 中注册:
services.AddSingleton<IApplicationData, ApplicationData>();
用法:
public class ValuesController : ControllerBase
{
readonly IApplicationData _applicationData;
public ValuesController(IApplicationData applicationData)
{
_applicationData = applicationData;
}
[HttpGet]
public IActionResult Get()
{
string data = _applicationData.ProductMainPictureFolder;
string data2 = _applicationData.GetProductPicturePath();
string data3 = _applicationData.GetNewPath();
return Ok();
}
}
推荐阅读
- rust - 如何知道服务器何时收到整个请求?
- angular - 下拉列表取决于第一个的选择
- laravel - Laravel 基于自的多态关系
- sql-server - 收到此错误:链接服务器“NS64”的 OLE DB 提供程序“MSDASQL”报告错误
- java - 如何通过java中的API从url获取图像?
- python - 设置一个常见的合理比例以显示具有单个图例的热图子图
- nearprotocol - NEAR 中有多少种交易类型?
- python - 使用 mkdir 创建目录并在 python 中循环时出错
- python - 使用 Python Flask 将文件上传到 IBM COS
- json - 无法在 Swift 中展开和折叠 TableViewCell