Search code examples
c#.netstatic-linking

Static link classes - need to know calling project name


My Setup :

Project A

Class Log
{
  public static void WriteLog(string msg)
 {
    Trace.write(GetTimestamp(), GetAppDominNameCallingWriteLog(), msg);
 }
}

Project B contains Static link Log.cs (Add as link)

Project C contains Static link Log.cs (Add as link)

Project D contains Static link Log.cs (Add as link)

Using one log file for all the project. Now I need to get the project name (GetAppDominNameCallingWriteLog()) in the Log class. How can i achieve this without passing Project name to WriteLog().

e.g. Project C calls Log.Writelog("logging msg") the result should be 201511121232 Project C logging msg

Project D calls Log.Writelog("logging msg") the result should be 201511121232 Project D logging msg

Tried with Thread.AppDomain(), it always return Project A.

Sorry I forgot to add this case : Project C is referenced in Project A.


Solution

  • You can find out the executing project using the below code

    AppDomain.CurrentDomain.FriendlyName;
    

    I have also checked this with the Thread class. It returns the result correctly

    System.Threading.Thread.GetDomain().FriendlyName;
    

    UPDATE

    Based on the additional information provided in the comments, you can identify the calling Assembly using Reflection

    System.Reflection.Assembly.GetCallingAssembly().FullName;
    

    Working Example

    static void Main(string[] args)
        {
            //Direct call to the Log class from ConsoleApplication3
            Log.Write();
    
            //Indirect call to the Log class through a Class Library called ClassLibrary1
            Class1.LogIt();
    
            Console.ReadLine();
        }
    

    And the output is

    Sample Output