简体   繁体   中英

c#: Check which project is calling class library

I have two projects which is calling a Class Library. Can i in my Class Library check which project is calling the Library?

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)

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);
    }
}

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()

如果您要查找的是主应用程序程序集,则正确的调用是Assembly.GetEntryAssembly()。FullName仅是我的2¢

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;
    }
}

如果您以某种方式追求安全性,则可能需要.NET代码访问安全性

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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