在ASP.NET Core中全局重用变量

时间:2019-01-27 07:44:25

标签: c# asp.net-core design-patterns

我必须强迫这些变量在我要使用的每个变量上重用,这使我很难。我需要创建一个类来定义这些变量,并在整个程序中使用它们。我该怎么办?

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);

1 个答案:

答案 0 :(得分:9)

您可以使用单例课程,这里是:

接口:

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>();

用法:

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();
    }
}