开发者

c#: Check which project is calling class library

I have two projects which is calling a Class Library. Can i in m开发者_如何学运维y 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()


if what you are looking for is the main application assembly, then the correct call is Assembly.GetEntryAssembly().FullName just my 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;
    }
}


If you're after security (in some way), the .NET Code Access Security may be what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜