Reputation: 3178
I have two projects which is calling a Class Library. Can i in my Class Library check which project is calling the Library?
Upvotes: 1
Views: 1520
Reputation: 38580
Assembly.GetCallingAssembly() will give you a reference to the assembly that invoked the method in which you put that line of code. I think this is exactly what you are asking but it is rare that a library should ever care about its caller so you may want to have a think about whether the approach is, indeed, correct.
// in Assembly 1
public class Assembly1Class
{
public void SomeMethod()
{
assembly2ClassInstance.SomeAPIMethod();
}
}
// in Assembly 2 (the library)
public class Assembly2Class
{
public void SomeAPIMethod()
{
Debug.WriteLine(Assembly.GetCallingAssembly().FullName;
}
}
Upvotes: 1
Reputation: 11
if what you are looking for is the main application assembly, then the correct call is Assembly.GetEntryAssembly().FullName just my 2¢
Upvotes: 1
Reputation: 82096
Why not store a unique value for each project in the App.Config file and then read this value from within your class library. Depending on what project (application) you are running it should pick up the correct application config. Or even just check the System.Reflection.Assembly.GetCallingAssembly().GetName().Name()
Upvotes: 2
Reputation: 23759
If you're after security (in some way), the .NET Code Access Security may be what you want.
Upvotes: 0
Reputation: 32900
Hmm...that doesn't sound good to me. What you're trying to achieve is to create a dependency from your class-library -> project which should instead be project -> class library dependency.
From my point this is "not" achievable and if so just hardly and is not considered good practice. A good class library should be of general purpose and should not change behavior depending on its caller.
(Maybe you could describe in more detail the nature of your problem, so I could help you better and find a better solution)
Upvotes: 3
Reputation: 57936
If that projects have different namespaces, you can use StackTrace
to build your call stack:
public static void Main()
{
StackTrace stackTrace = new StackTrace();
StackFrame[] stackFrames = stackTrace.GetFrames();
foreach (StackFrame stackFrame in stackFrames)
{
Console.WriteLine(stackFrame.GetMethod().Name);
}
}
Upvotes: 2