Asp.Net MVC - 所有控制器的通用数据

时间:2010-01-25 17:33:46

标签: asp.net-mvc asp.net-mvc-2 controller

设置:(使用Asp.Net MVC 2 RC,实体框架,SQL Server,VS2008)

我的好友和我正在开发一个项目,该项目将有不同的域名指向它。我们希望从请求中获取域(网站)并使用它来驱动数据。该网站数据需要成为所有控制器的一部分。

  

实施例。 domain1.website.com的数据将   与数据不同   domain2.website.com,那些将是   与website2.com的数据不同。   该网站的外观是相同的   所有这些,但数据是不同的。

我设置了一个我所有其他控制器继承的BaseController。但我不喜欢它。

BaseController:

public class BaseController : Controller
{
    private Website _website;
    private readonly IWebsiteRepository _websiteRepository;

    public BaseController(IWebsiteRepository websiteRepository)
    {
        _websiteRepository = websiteRepository;
    }

    public Website CurrentWebsite { get; }
}

这个问题是我现在需要将IWebsiteRepository传递给每个控制器的基础:

public class BioController : BaseController
{
    private readonly IBiographyRepository _bioRepository;

    public BioController(IBiographyRepository bioRepository, IWebsiteRepository websiteRepository) 
        : base(websiteRepository)
    {
        _bioRepository = bioRepository;
    }
}

这是我的问题

  1. 有没有更好的方法来处理指向一个项目并过滤数据的多个域?
  2. 是否有更好的方法在每个控制器中都有网站对象?
  3. 更新

    抱歉,我忘了添加它。我已经在使用IoC(结构图)。我的问题更多的是:

    1. 我应该用其他东西替换BaseController吗? ActionFilter?
    2. 有没有办法设置它所以我没有必要将IWebsiteRepository传递给基类?
    3. 有没有更好的方法来处理用于数据的域?

2 个答案:

答案 0 :(得分:1)

我实际上喜欢通过构造函数注入注入存储库的想法。它可以让您更轻松地测试控制器,因为您可以简单地传入模拟存储库。另一种方法是使用静态工厂类从请求中获取存储库,但使用静态类会使单元测试更加困难。

我要做的一个改进是为控制器设置一个默认构造函数,该构造函数使用带有空值的参数调用构造函数。在带有参数的构造函数中,如果提供的参数为null,则实例化正确的存储库。这样您就不需要实现控制器工厂来构建带有参数的控制器;默认的控制器工厂可以使用无参数构造函数,你仍然可以获得构造函数注入的好处。

 public BaseController() : this(null) { }

 public BaseController( IWebsiteRepository websiteRepository )
 {
     this._websiteRepository = websiteRepository ?? new WebsiteRepository();
 }

答案 1 :(得分:1)

相关问题