我在存储库中有一个具有非常复杂的业务逻辑的方法.我刚刚读到存储库中应该没有业务逻辑.
从这种方法中删除业务逻辑将要求我在两个其他存储库之间分配逻辑(因为它涉及另外两个实体).
然后我的问题是 - 我应该用什么模式来实现这个复杂的逻辑?它需要使用这三个存储库,但我不能将它放在控制器中,因为我需要重用它.谢谢您的帮助.
复杂的业务逻辑通常会进入服务层.服务可能依赖于一个或多个存储库来对您的模型执行CRUD操作.因此,表示业务操作的单个服务操作可以取决于多个简单操作.然后,您可以在控制器和其他应用程序中重用此服务层.
显然,您的服务不应该依赖于特定的存储库实现.为了在服务层和存储库之间提供较弱的耦合,您可以使用接口.这是一个例子:
public interface IProductsRepository { }
public interface IOrdersRepository { }
...
public interface ISomeService
{
void SomeBusinessOperation();
}
public class SomeServiceImpl: ISomeService
{
private readonly IProductsRepository _productsRepository;
private readonly IOrdersRepository _ordersRepository;
public SomeServiceImpl(
IProductsRepository productsRepository,
IOrdersRepository ordersRepository
)
{
_productsRepository = productsRepository;
_ordersRepository = ordersRepository;
}
public void SomeBusinessOperation()
{
// TODO: use the repositories to implement the business operation
}
}
Run Code Online (Sandbox Code Playgroud)
现在剩下的就是配置你的DI框架,将这个特定的服务注入你的控制器.
public class FooController : Controller
{
private readonly ISomeService _service;
public FooController(ISomeService service)
{
_service = service;
}
public ActionResult Index()
{
// TODO: Use the business operation here.
}
}
Run Code Online (Sandbox Code Playgroud)
您可以看到接口如何允许我们在层之间提供弱耦合.所有管道都由DI框架执行,一切都是透明的,并且易于单元测试.
归档时间: |
|
查看次数: |
2018 次 |
最近记录: |