我目前正在构建一个ASP.Net MVC 4 SAAS应用程序(C#),我一直坚持设计计划。我的意思是,如果客户选择Plan A
,他们应该可以访问某些内容,如果他们选择Plan B
,他们就可以访问其他人等等。
我坚持使用的部分是与所有操作共享帐户计划的最佳做法。我意识到全局变量是不好的做法,但我真的不想到数据库进行往返行程来获得每个行动的计划。
我正在考虑做的事情就像This SO answer,他们只是声明一个静态模型并在某个时候设置它并稍后访问它。在您看来,这是最好的方法吗?有更好的方法吗?
答案 0 :(得分:5)
我认为最佳做法是在项目中加入IoC并向控制器注入配置对象。
控制器的示例代码:
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以指定此配置对象的单一范围。如果您需要将此模式应用于所有控制器,您可以创建一个基本控制器类来重用代码。
您的IConfigService
public interface IConfigService
{
string ConfiguredPlan{ get; }
}
您的ConfigService:
public class ConfigService : IConfigService
{
private string _ConfiguredPlan = null;
public string ConfiguredPlan
{
get
{
if (_ConfiguredPlan == null){
//load configured plan from DB
}
return _ConfiguredPlan;
}
}
}