Robert McCabe
Robert McCabe

Reputation: 11

Determine if code is called from within the same assembly

I would like to lock down classes within my assembly to stop them being called from other classes within the same assembly. So in other words, no sideways calls within the assembly.

I was going to write some validation in the class calls to make sure they are not called from within the same assembly. How can I determine this using reflection?

So its the following scenario:

Assembly1
----------
Class 1A

Assembly2
----------
Class 2A
Class 2B

So class 2A cannot call class 2B. But Class 1A can call Class 2A or Class 2B.

Upvotes: 1

Views: 420

Answers (3)

Oded
Oded

Reputation: 499002

What you are asking about is not possible with the existing access modifiers.

You cannot make a class public to other assemblies but internally private.

If you split out your Class2B to a different assembly and make it internal, you can also set the InternalsVisibleToAttribute to Assembly1.

What this will achieve is that Class2A can't access it, but Class1A can.


You can do some runtime checks using reflection as well - as the answer by Christian.K details.

Upvotes: 2

Christian.K
Christian.K

Reputation: 49260

Why do you put them in the same assembly in the first place?

Rather put 2B and 2A in there own assemblies, marking the classes as internal. The provide the assembly-level attribute InternalsVisibleTo to allow "Assembly1" to access the internals of "Assembly2B" and "Assembly2A" respectively.

Using reflection, you would still be able to circumvent this.

Using such a mechanism (or any other one, handcrafted "caller checking", whatever) for security purposes is not advisable anyway. If you want to do it for "architectural" purposes, you could go with what was suggested above and possible use tools like NDepend or a custom FxCop/CodeAnalysis rule. You could validate that your rules are not broken during build time.

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109567

How about:

if (Assembly.GetCallingAssembly() == Assembly.GetExecutingAssembly())
{
    // Throw some exception
}

Seems a pretty weird thing to do though...

Upvotes: 0

Related Questions