我必须强制这些变量在我想使用的每个变量上重用,这让我很困难。我需要创建一个类来定义这些变量并在整个程序中使用它们。我怎样才能做到这一点?
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 容器中注册:
services.AddSingleton<IApplicationData, ApplicationData>();
Usage:
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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)