(注入的)服务之间的依赖关系 [英] Dependencies between (injected) services

查看:295
本文介绍了(注入的)服务之间的依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Web应用程序,并具有用于业务逻辑的服务层.这些服务被注入到控制器中.现在,我想知道在以下情况下的最佳实践是什么.

I'm building a web application and have a service layer for business logic. These services are injected into the controllers. Now, I'm wondering what the best practice is in the following situation.

我有一个AuthenticatorService,毫不奇怪,它负责身份验证.当用户尝试进行身份验证时,这显然应该记录下来.这是LoggerService可以处理的.

I have a AuthenticatorService that, unsurprisingly, is responsible for authentication. When a user attempts authenticating, this is clearly something that should be logged. That's something a LoggerService can handle.

现在,我将LoggerService注入到AuthenticatorService中,但是在服务之间具有依赖关系并不十分干净...

Right now, I'm injecting a LoggerService into the AuthenticatorService, but having dependencies between services does not feel very clean...

我将具体类型绑定到接口,因此从逻辑上讲我会说很好-显然,绝对可以肯定,注入的服务将永远没有理由依赖于另一个,从而产生了循环依赖.

I'm binding concrete types to interfaces, so logically speaking I would say this is fine - obviously given that it is absolutely certain that the injected service will never have a reason to rely on the other, thus creating a circular dependency.

我对阅读别人如何解决这个问题非常感兴趣-或者,这是否根本不是问题.

I'm very interested in reading how others are solving this problem - or, whether it is not a problem at all.

请不要建议从控制器处理日志记录-这只是一个示例,在一种服务可能要调用另一种服务的情况下,还有很多其他可以想象的情况.

Please do not suggest handling logging from the controller - this is just an example, and there's a lot more situations imaginable where one service might want to call another.

推荐答案

我对阅读别人如何解决这个问题非常感兴趣-或者,这是否根本不是问题.

I'm very interested in reading how others are solving this problem - or, whether it is not a problem at all.

是的,这是一个问题-实际上,这是最常被问到的问题之一.此问题的名称是横切关注点.解决问题的方法有几种.

Yes, it is a problem - in fact, it is one of the most asked about problems. The name of this problem is crosscutting concerns. There are several different ways that the problem could be tackled.

  1. 特定于框架的-在MVC/WebApi中,有可以在特定控制器,操作或每个请求中运行逻辑的过滤器.
  2. 使用第三方面向方面的编程(AOP)框架.
  3. 使用常见的设计模式,例如代理代理示例,其中使用了.NET RealProxy类.
  4. 拦截,内置在几个主要依赖项注入框架中的功能.
  1. Framework-specific - in MVC/WebApi, there are filters that can run logic in specific controllers, actions, or on every request.
  2. Using a 3rd party Aspect-Oriented Programming (AOP) framework.
  3. Using common design patterns such as proxy or decorator. Here is an proxy example using the .NET RealProxy class.
  4. Interception, a feature built into several major dependency injection frameworks.

这篇关于(注入的)服务之间的依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆