简体   繁体   English

c#:检查哪个项目正在调用类库

[英]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. 您要实现的目标是从类库->项目创建一个依赖项,而应该是project->类库依赖项。

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: 如果该项目具有不同的名称空间,则可以使用StackTrace构建调用堆栈:

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. 为什么不为每个项目在App.Config文件中存储一个唯一值,然后从类库中读取该值。 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() 甚至只是检查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. Assembly.GetCallingAssembly()将为您提供一个引用,该引用调用了您放置该行代码的方法。 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代码访问安全性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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