gpt4 book ai didi

asp.net-mvc - Asp.Net MVC - 所有 Controller 的通用数据

转载 作者:行者123 更新时间:2023-12-01 04:20:22 25 4
gpt4 key购买 nike

设置:(使用 Asp.Net MVC 2 RC、Entity Framework、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,我的所有其他 Controller 都继承自该 Controller 。但我不喜欢它。

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

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

public Website CurrentWebsite { get; }
}

问题是我现在需要将 IWebsiteRepository 传递给每个 Controller 的基础:
public class BioController : BaseController
{
private readonly IBiographyRepository _bioRepository;

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

这是我的问题
  • 有没有更好的方法来处理指向一个项目的多个域并过滤数据?
  • 有没有更好的方法让每个 Controller 中都有网站对象?

  • 更新

    抱歉,我忘记添加了。我已经在使用 IoC(结构图)。我的问题更多的是:
  • 我应该用其他东西替换 BaseController 吗? Action 过滤器?
  • 有没有办法设置它,所以我不必将 IWebsiteRepository 传递给基类?
  • 有没有更好的方法来处理用于数据的域?
  • 最佳答案

    我实际上喜欢通过构造函数注入(inject)来注入(inject)存储库的想法。它将使测试 Controller 变得更加容易,因为您可以简单地传入模拟存储库。另一种方法是使用静态工厂类从请求中获取存储库,但使用静态类会使单元测试更加困难。

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

     public BaseController() : this(null) { }

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

    关于asp.net-mvc - Asp.Net MVC - 所有 Controller 的通用数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2134233/

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