在 C# 中,具有典型的依赖注入服务设置。我注册了自己的定制服务并且运行良好。但是,我发现它有时会被调用(注入),这是我没有预料到的。 所以我想调试并知道什么代码想要注入我的服务?我不知道如何做到这一点。
示例:
// Program startup I register my service as normal.
services.AddTransient<MyCustomService>();
// And other stuff...
services.AddTransient<SomeOtherThing>();
services.AddTransient<AndAnother>();
services.AddTransient<AndMore>();
public class MyCustomService
{
public MyCustomService()
{
// My service works fine, but can it know who is requesting it?
// WHO IS REQUESTING ME FROM DI?
// Note that this is not intended for some weird hacky functionality,
// rather I'm trying to debug why my service is being invoked more than expected.
}
}
// Some other services/controllers/etc that are pulling in MyCustomService from DI
...
public SomeOtherThing(MyCustomService mcs) { ... }
...
public AndAnother(MyCustomService mcs) { ... }
...
public AndMore(MyCustomService mcs) { ... }
...
在您的服务中放置一个断点。当在这些意外时间命中断点时,请检查Call Stack以找出服务调用的来源。如果您有 VS Enterprise,您甚至可以检查调用堆栈作为可视化地图。