【发布时间】:2020-02-04 21:11:55
【问题描述】:
本质上,我希望能够确定我的服务中调用者类的命名空间。服务实例化使用默认的 ASP.NET Core DI 进行。可能会出现进一步的障碍,因为我想在基类的构造函数中确定调用者,而不是直接在实例化的服务中。
我怀疑我知道我的问题的答案,但如果它真的发生了,那也不会是我见过的更疯狂的事情了。
编辑
示例代码
// First caller
namespace Example.Assembly.One
{
public class CallerOne
{
consctructor(Service service)
void WhichCallerAmI() { return this.service.ReturnCaller() }
...
}
}
// Second caller
namespace Example.Assembly.Two
{
public class CallerTwo
{
consctructor(Service service)
void WhichCallerAmI() { return this.service.ReturnCaller() }
...
}
}
// Service
namespace Example.Service
{
public class Service : BaseService
{
consctructor() : base()
public void ReturnCaller()
{
if (this.namespace == "Example.Assembly.One")
{
return "First caller";
}
return "Second caller";
}
}
}
// Base service
namespace Example.Service
{
public class BaseService
{
consctructor(Service service)
{
// Determine namespace of caller here
this.namespace = <insert-answer-here>
}
}
}
// demo
// These callers can be controllers or other services
var firstCaller = new CallerOne()
var secondCaller = new CallerTwo();
// firstResult now contains "First Caller"
var firstResult = firstCaller.WhichCallerAmI();
// secondResult now contains "Second Caller";
var secondResult = secondCaller.WhichCallerAmI();
XY 问题
示例中的 Callers 表示单独的微服务 Web 项目中的数据服务,每个项目都使用单独的数据库。我试图解决的问题是为一个实体重用相同的服务代码,在所有或部分单独的数据库中重复。我的想法是根据调用者类的命名空间注入相关的DbContext,因为无论哪种方式我们都遵循严格的命名约定。
【问题讨论】:
-
这可能是XY problem。提供minimal reproducible example 以阐明您的特定问题或添加其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
-
你为什么关心这个?这反转依赖注入。你想解决的真正问题是什么?在运行时执行此操作的简单方法是使用例如StackTrace 来查找调用方法,但为什么要这样做?如果调用者的类型很重要,为什么不将其作为泛型类型参数传递?
标签: asp.net-core dependency-injection