gpt4 book ai didi

c# - ASP.NET MVC 4 中的全局变量

转载 作者:行者123 更新时间:2023-12-02 21:55:30 25 4
gpt4 key购买 nike

我目前正在构建一个 ASP.Net MVC 4 SAAS 应用程序 (C#),并且一直致力于设计计划。我的意思是,如果客户选择计划 A,他们应该有权访问某些内容,如果他们选择计划 B,他们就可以访问其他内容,依此类推。

我坚持的部分是与所有操作共享帐户计划的最佳实践。我意识到使用全局变量是不好的做法,但我真的不想往返数据库来获取每个操作的计划。

我想做的事情类似于 This SO answer他们只是声明一个静态模型并在某个时刻设置它并稍后访问它。您认为这是最好的方法吗?有更好的办法吗?

最佳答案

我认为最佳实践是您应该在项目中包含 IoC 并向 Controller 注入(inject)配置对象。

Controller 的示例代码:

public class YourController : Controller
{
private IConfigService _configService;

//inject your configuration object here.
public YourController(IConfigService configService){
// A guard clause to ensure we have a config object or there is something wrong
if (configService == null){
throw new ArgumentNullException("configService");
}
_configService = configService;
}
}

您可以配置 IoC 以指定此配置对象的单例范围。如果您需要将此模式应用于所有 Controller ,您可以创建一个基本 Controller 类来重用代码。

您的 IConfigService

public interface IConfigService
{
string ConfiguredPlan{ get; }
}

您的配置服务:

public class ConfigService : IConfigService
{
private string _ConfiguredPlan = null;

public string ConfiguredPlan
{
get
{
if (_ConfiguredPlan == null){
//load configured plan from DB
}
return _ConfiguredPlan;
}
}
}
  • 此类可以轻松扩展以包含更多配置,例如连接字符串、默认超时...
  • 我们正在向 Controller 类传递一个接口(interface),我们可以在单元测试期间轻松模拟该对象。

关于c# - ASP.NET MVC 4 中的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17896014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com