c# - AggregateService 是否应该作为一个容器来存储公共(public)依赖?

标签 c# asp.net-mvc dependency-injection

我有一个基本 Controller 类,它使用 autofac 中的聚合服务来注入(inject)其依赖项。在从基本 Controller 派生的类中,我需要访问作为聚合容器一部分的服务。哪种方法更好?

public Interface ICommonControllerDependencies
{
    ICookieService CookieService{ get; }
    IAuthenticationService AuthenticationService{ get; }
}

public abstract class BaseController : Controller
{
    protected readonly ICommonControllerDependencies Dependencies;

    protected BaseController(ICommonControllerDependencies dependencies)
    {
        this.Dependencies = dependencies;
    }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.ViewData[UserName] = Dependencies.AuthenticationService.UserName;

        base.OnActionExecuting(filterContext);            
    }
     protected ActionResult RedirectToDefaultPage()
    {
        var page = Dependencies.CookieService.GetDefaultPageCookie(Request, RouteData);
        //Do Something
    }  

}

public class BaseReportController : BaseController
{
    public BaseReportController(ICommonControllerDependencies dependencies)
        : base(dependencies)
   {
        _cookieService = dependencies.CookieService;
   }
}

public class BaseReportController : BaseController
{
    public BaseReportController(
        ICookieService cookieService, 
        ICommonControllerDependencies dependencies)
        : base(dependencies)
    {
        _cookieService = cookieService;
    }
}

最佳答案

AggregateService旨在将您的子类与父类(super class)中的更改隔离开来,并在不破坏子类的情况下启用父类(super class)中的更改。 如果您选择选项 1,您会将子类耦合到您的父类(super class),从而失去预期的隔离。

在不了解您的设计的情况下,我会选择选项 2。我不认为我可以预期 ServiceA 始终存在。在子类中显式依赖于 IServiceA,该类可以快乐地生活,而无需了解父类(super class)内部发生的变化。

关于c# - AggregateService 是否应该作为一个容器来存储公共(public)依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9012577/

相关文章:

C# - OxyPlot 如何将绘图添加到窗口窗体

c# - 如何检查线程代码是否在 try-catch block 中运行

c# - 通过调用另一个类的函数将数据传递到非静态列表框

asp.net - ViewEngines 会影响 Asp.Net MVC 的性能吗?

c# - Linq to SQL、SQL Server 2008 和优化

asp.net-mvc-3 - 如何使用 Entity Framework 4.1 在 ASP.NET MVC 3 模型类的构造函数中注入(inject)依赖项?

java - 我如何在 JavaFX Controller 中使用 Guice?

c# - Web API 核心 2.2 中的延迟加载

c# - NopCommerce 添加新表 - 无效的列名称 'Product_Id1'

c# - 依赖注入(inject) IDbConnection SqlConnection