【发布时间】:2019-03-29 15:42:21
【问题描述】:
这是使用 Microsoft.Extensions.DependencyInjection 的 dotNet core 2.2 项目。
我有 3 节课。 A 类在构造函数中使用 B 类。 B类使用C类,C类使用ITenant接口。
ITenant 确定将使用哪个数据库。
示例:
public A(IB b)
public B(IC c)
public C(ITenant t)
它们在注入容器中的设置如下:
services.AddTransient<IA, A>();
services.AddTransient<IB, b>();
services.AddTransient<IC, c>();
services.AddTransient<ITenant , HttpTenant>()>();
在 web 项目中,控制器使用 Class A 作为构造函数参数和容器 createClass A 及其所有依赖项。 ITenant (HttpTenant) 的实现从 HTTP 请求标头中提取租户名称,并从配置文件中获取数据库信息。一切正常。
现在我需要从不涉及 HTTP 请求的 Windows 服务调用它。我有一个响应消息队列的处理程序,A 类是一个构造参数。对于 windows 服务,我有一个不同的 ITenant (WindowServiceTenant):
services.AddTransient<ITenant , WindowServiceTenant>()>();
我不知道如何将租户代码放入 WindowServiceTenant。
- 租户是在运行时根据从消息队列中读取的值确定的。
- 当我的处理程序被实例化时,WindowServiceTenant 也被实例化了。
- 在设置处理程序之前我不认识租户。
我需要获取 WindowServiceTenant 实例的引用并提供租户。或者,此实现 WindowServiceTenant 需要对启动实例化的处理程序的引用。
有什么想法吗?
【问题讨论】:
标签: c# dependency-injection .net-core