如何确保只能从特定的 dll 中调用方法

How to ensure that a method can only be called from a specific dll

我需要为单元测试准备我的数据库,因此我想在设置方法中删除数据。

但是,除了单元测试 dll 之外,我不想成为任何其他人,以便能够在我的数据访问层中调用我的 DeleteAllData() 方法。可以做什么?

您可以对两个程序集进行签名,然后使用 InternalsVisibleTo 属性使单元测试程序集成为唯一能够看到 internal 的程序集。你需要把你只想暴露给单元测试项目的所有方法、属性和类internal

InternalsVisibleToAttribute 上的 MSDN:

Specifies that types that are ordinarily visible only within the current assembly are visible to a specified assembly.

internal关键字标记。来自 MSDN docs:

The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly

您可以在 DeleteAllData() 方法中组合使用 Assembly.GetCallingAssembly() and interrogation of the call stack 来确保您的方法只被您期望的方法调用。

您可能需要 prevent the jitter inlining your method calls 以确保调用程序集方法和调用堆栈在到达您的 DeleteAllData() 方法时得到保留。

调用堆栈可能就足够了,但可能还需要调用程序集。

我没有试过这个,但我认为它在理论上应该可行。

虽然其他人已经建议如何限制代码调用您的方法,但它们不会创建安全边界并且可能被欺骗(除非您签署两个程序集并验证证据)。

在您的业务逻辑中有一个名为 DeleteAllData 的方法对我来说听起来很可怕。如果此方法仅用于单元测试,我可能会将其移至单元测试程序集。如果那不可能,我至少会把代码放在 compiler directive 中,只在调试模式下编译。

我还有另一种方法来实现问题中提到的事情。

如果您使用的是 VSTS 单元测试。

在 class 中将方法设置为私有,以便其他 classes 和程序集无法访问它。

现在要从单元测试中调用私有方法,请使用 PrivateObject

这是 PrivateObject 的 Microsoft 文档:- link

如何使用私有对象:- link