在ASP.NET MVC 4全局变量 [英] Global Variables in ASP.NET MVC 4
问题描述
我目前正在建立一个ASP.Net MVC 4 SaaS应用程序(C#)和我被困在设计计划。我的意思是,如果顾客拿起 A计划
他们应该有机会获得一些事情,如果他们选择 B计划
他们可以访问给别人等等。
I'm currently building an ASP.Net MVC 4 SAAS application (C#) and am stuck on designing the plans. I mean if a customer picks Plan A
they should have access to some things and if they pick Plan B
they get access to others and so on.
这是我卡上的部分原因是要与所有的行动共享帐户的计划的最佳实践。我实现具有全局变量是不好的做法,但我真的不希望采取往返数据库来获取每一个行动计划。
The Part that I'm stuck on is be best practice of sharing the account's plan with all of the actions. I realize having global variables are bad practice and all but I really don't want to take round trips to the DB to get the plan on every action.
我在想什么做的是一样的东西这SO回答,他们只需要声明一个静态的模型,并将其设置在某些时候和访问它以后。在您看来,这是这样做的最佳方式?有没有更好的办法?
What I'm thinking of doing is something like This SO answer where they just declare a static model and set it at some point and access it later on. In your opinion, is this the best way of doing this? is there a better way?
推荐答案
我认为最好的做法是,你应该包括国际奥委会项目,并注入一个配置对象到控制器。
I think best practice is you should include an IoC in your project and inject a configuration object to your controller.
控制器的例子code:
Example code of a 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指定singleton作用域此配置对象。如果你需要这种模式适用于所有的控制器,你可以创建一个基础类重用code。
You could configure your IoC to specify singleton scope for this configuration object. In case you need to apply this pattern to all your controllers, you could create a base controller class to reuse code.
您IConfigService
Your IConfigService
public interface IConfigService
{
string ConfiguredPlan{ get; }
}
您的ConfigService:
Your ConfigService:
public class ConfigService : IConfigService
{
private string _ConfiguredPlan = null;
public string ConfiguredPlan
{
get
{
if (_ConfiguredPlan == null){
//load configured plan from DB
}
return _ConfiguredPlan;
}
}
}
- 此类很容易扩展到包括更多的配置类似的连接字符串,默认的超时时间,...
- 我们正在传递给我们的控制器类的界面,很容易让我们在单元测试过程模拟此对象。
这篇关于在ASP.NET MVC 4全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!