我有一个基本 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/