gpt4 book ai didi

c# - 将服务引用传递给另一个服务层是不好的做法吗?

转载 作者:太空狗 更新时间:2023-10-29 21:30:42 24 4
gpt4 key购买 nike

我有一个 C# MVC 应用程序,我按以下方式分解它:查看 -> Controller -> 服务 -> 存储库

我使用瘦 Controller 实践,每个 View 都有一个从相关服务返回的唯一 View 模型。

快速示例:查看:/NewAppointment/Step1

它的 Controller 看起来像这样:

public ActionResult Step1()
{
return View(_appointmentService.Step1GetModel() );
}

约会服务层看起来像这样:

public Step1Model Step1GetModel()
{
return new Step1Model();
}

因此,我在整个应用程序中使用了多个不同的服务层,每个服务层都实现了一个不同的接口(interface)。

当我需要让一个服务层与另一个服务层交互时,我的问题就来了。在这种情况下,是将接口(interface)引用传递给服务调用更好,还是让 Controller 处理收集所有数据,然后将相关结果传递回服务?

例子:

假设我想在默认情况下用客户的信息填充我的 View 模型。我看到的两种方法是:

将客户接口(interface)引用传递给约会服务,然后让约会服务调用客户服务中适当的 GetCustomer 方法...

在代码中:

 private ICustomerService _customerService;
private IAppointmentService _appointmentService;

public ActionResult Step1()
{
var viewModel = _appointmentService.Step1GetModel( _customerService );
return View(viewModel);
}

让 Controller 处理获取客户的逻辑,然后将该结果传递给预约服务。

在代码中:

private ICustomerService _customerService;
private IAppointmentService _appointmentService;

public ActionResult Step1()
{
var customer = _customerService.GetCustomer();
var viewModel = _appointmentService.Step1GetModel( customer );
return View(viewModel);
}

我很纠结哪种做法更好。第一个使 Controller 保持美观和精简,但在预约服务和客户服务之间创建了服务间依赖关系。第二个将更多逻辑放入 Controller 中,但保持服务完全独立。

有人知道哪种做法更好吗?

谢谢~

最佳答案

纯粹从概念上考虑他,我认为让您的服务了解您的 View 模型是没有意义的。首先拥有 Controller 的主要原因之一是将 View 逻辑与业务逻辑分开,但如果您的服务返回 View 特定数据,那么它们本质上与您的业务逻辑相关联。

理想情况下,我希望该方法看起来像这样:

public ActionResult Step1()
{
var customer = _customerService.GetCustomer();
var appointment = _appointmentService.GetAppointmentFor(customer);

var viewModel = new Step1ViewModel(customer, appointment);

return View(viewModel);
}

不过,为了更直接地回答您的问题,我认为您的服务相互了解是很好的,它们属于同一概念层。

另外,还有一件事......

听起来你有很多平行的类层次结构,还有服务、存储库和 Controller 。使用工作单元模式和强大的 ORM 来做这样的事情可能更有意义:

public MyController(IUnitOfWork unitOfWork)...

public ActionResult Step1()
{
var customer = unitOfWork.Find<Customer>();
var viewModel = new Step1ViewModel(customer.Appointment);
return View(viewModel);
}

毕竟,您的应用程序的值(value)在于模型,而不是服务。

关于c# - 将服务引用传递给另一个服务层是不好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4318049/

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