I have created a DLL that will gather information from the AssemblyInfo.cs. In the class constructor I am using Reflection to get the top-most application that is running.
public class AppInfo() { public AppInfo() { System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly(); if (assembly == null) assembly = System.Reflection.Assembly.GetCallingAssembly(); //code to gather needed information } }
How this is intended to be used is if I call this from any DLL in a given application, MyApp, that lets say the name will always be ‘MyApp’. Retrieving that information is not a problem and it works great in Windows Services and Windows Applications. My question is this: How do I get the Assembly of the top-most Website?
I have found a few articles and I can get the information in the Global.asax.cs by moving the AssemblyInfo.cs for the Website out of the App_Code folder and into the root of the Website. Then by adding a compilerOption to the physical path of the AssemblyInfo.cs
<compiler language='c#;cs;csharp' extension='.cs' compilerOptions='C:\Sandbox\MyWebSite\AssemblyInfo.cs' type='Microsoft.CSharp.CSharpCodeProvider,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' warningLevel='4'>
Using that I am able to retrieve information in the AssemblyInfo.cs for the Website through System.Reflection.Assembly.GetExecutingAssembly(). Now I can overload the constructor of my AppInfo class to accept an Assembly and retrieve information that way, but if another DLL that is used by MyWebSite creates a new AppInfo() I will get the assembly information of that DLL instead of the parent Website.
I know that if I was working with Web Apps instead of Web Sites I wouldn’t have this issue, but for reasons I won’t go into I am not able to use Web Apps. Any suggestions on how I can read information from the AssemblyInfo.cs of the Website I’m running in no matter what DLL I’m in?
EDIT: I need this to work for Web Sites, Windows Apps and Windows Services
If I understand you properly, the problem is that
Assembly.GetEntryAssembly()returns null in a Website andAssembly.GetCallingAssembly()is returning the wrong thing because you’ve got a chain of calls resulting in the website not being the immediate caller. If that’s the case, you could find the ‘Entry Assembly’ using the stack trace & walking back up the calling frames. The stack will be full of references from System.Web, etc as the call will have originated from deep within IIS somewhere, but you should be able to pick out the assembly you’re interested in by grabbing the lowest frame that you can positively identify as belonging to you. Note that this is pretty hacky, but I think it’ll get you what you want…Hopefully someone else will be able to come up with a less nasty way of doing it… but if you’re really stuck, this might help.