首页 > 解决方案 > 在 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);

标签: c#asp.net-coredesign-patterns

解决方案


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

界面:

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

推荐阅读