Mr-*_*mer 1 c# design-patterns 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);
Run Code Online (Sandbox Code Playgroud)
Moi*_*jik 10
您可以使用单例类,您可以:
接口:
public interface IApplicationData
{
string RootFolderName { get; }
string ProductPictureFolder { get; }
string ProductMainPictureFolder { get; }
string WebRootPath { get; }
string RootPath { get; }
string GetProductPicturePath();
string GetProductMainPicturePath();
string GetNewPath();
}
Run Code Online (Sandbox Code Playgroud)
具体实施:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
注册DI容器:
services.AddSingleton<IApplicationData, ApplicationData>();
Run Code Online (Sandbox Code Playgroud)
用法:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
212 次 |
| 最近记录: |