asp.net-mvc – Asp.Net MVC – 跨所有控制器的通用数据

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

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

Ex. Data for domain1.website.com will
be different than data for
domain2.website.com, and those will be
different than data for website2.com.
The look of the site is the same for
all these, but the data is different.

我设置了一个我所有其他控制器继承的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;
    }
}

这是我的问题

>有没有更好的方法来处理指向一个项目并过滤数据的多个域?
>有没有更好的方法在每个控制器中拥有Website对象?

UPDATE

对不起,我忘了添加它.我已经在使用IoC(结构图).我的问题更多的是:

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

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

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

 public BaseController() : this(null) { }

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