【发布时间】:2021-10-07 01:09:57
【问题描述】:
我有一个三层架构。
我无法使用构造函数注入,我需要访问我的业务代码中的服务,而我无权访问 HttpContext。
例如,在操作方法、过滤器或中间件中,我可以使用以下方式获取服务:
HttpContext.RequestServices.GetRequiredService<ITranslator>();
但在我的业务代码中,我无权访问HttpContext。
如何获取我的服务实例?
更新:
这是我的业务代码:
public class InvoiceBusiness
{
// for some reasons, I can't use constructor injection here
public void CalculateTranslationsInvoice(long customerId)
{
// I need to get an instance of ITranslator here, and a couple of other services.
// If this method was in a controller, I could use HttpContext.RequestServices.
// But here what should I do?
}
}
【问题讨论】:
-
听起来你在这里做错了什么。你能把你需要这个的地方,以及不允许你使用正常注入的代码贴出来吗?
-
@CamiloTerevinto,更新了问题。
-
"由于某些原因,我不能在这里使用构造函数注入" -> 这对我们来说还不够好。那些原因是什么?为什么你在那个班级也需要
CalculateTranslationsInvoice?
标签: c# asp.net-core dependency-injection