简体   繁体   English

在C#中,如何从引用的项目中获取调用项目的名称?

[英]In C#, how can I get the name of the calling project from within a referenced project?

I have three projects: My.Business, My.WebSite and My.WebService 我有三个项目:My.Business,My.WebSite和My.WebService

I need my logging class to be able to identify when a request is made from the website versus the web service. 我需要我的日志记录类,以便能够识别何时从网站请求请求到Web服务。 I used to have the web service running as a separate application underneath the web site, so I'd just use different config files, which worked fine. 以前,我曾将Web服务作为单独的应用程序在网站下面运行,所以我只使用了不同的配置文件,效果很好。 But I want the web service now to run under the same application. 但是我希望Web服务现在可以在同一应用程序下运行。

If I could figure out if the request was coming from My.WebSite or My.WebService, I'd be set, but I'm not sure how to do this. 如果我能确定请求是来自My.WebSite还是My.WebService,我会被设置,但是我不确定该怎么做。

  • Assembly.GetExecutingAssembly() returns back My.Business Assembly.GetExecutingAssembly()返回My.Business
  • Assembly.GetEntryAssembly() is null Assembly.GetEntryAssembly()为null
  • I could check the StackTrace, but that seems sloppy and how for back would I have to go? 我可以检查StackTrace,但这似乎草率,我该如何退后? Especially because the logging may be triggered by code in My.Business that was originally invoked from one of the other projects. 尤其是因为日志记录可能是由My.Business中最初从其他项目之一调用的代码触发的。

Since the web service requests end in ".asmx", the following concept works, but it just doesn't feel right. 由于Web服务请求以“ .asmx”结尾,因此可以使用以下概念,但是感觉不对。

return HttpContext.Current.Request.Path.IndexOf(".asmx") >= 0 ? "My.WebService" : "My.WebSite";

Thanks! 谢谢!

You should be able to use Assembly.GetCallingAssembly(): 您应该能够使用Assembly.GetCallingAssembly():

return Assembly.GetCallingAssembly().FullName;

This will return the assembly that invoked the current executing method, so you can capture whoever is calling into your My.Business assembly that way. 这将返回调用当前执行方法的程序集,因此您可以捕获以这种方式调用My.Business程序集的任何人。

With that said, I tend to agree with the comment above by Meirion Hughes. 话虽如此,我倾向于同意梅里昂·休斯的上述评论。 You might like to consider passing in any info that is required to your logging class, especially if it is likely to be used across more applications in the future. 您可能想考虑将任何必需的信息传递给日志记录类,尤其是如果将来有可能在更多应用程序中使用它时。

this.GetType().Assembly.FullName将为您提供当前类的程序集名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM