c# – Is it possible to restrict who can use an assembly's public classes?

Question:

The scenario is as follows:

I have an AssemblyProtegido.dll written in .NET that contains public classes. I would like only specific assemblies to be able to consume such classes.

AssemblyProtegido.csproj

public class ClasseProtegida
{
    public void AlgumMetodo() {...}
}

Allowed.csproj

using AssemblyProtegido;

class Classe1 {
    //OK
    private ClasseProtegida obj = new ClasseProtegida();
}

Third.csproj

using AssemblyProtegido;

class Classe1 {
    //lançaria algum tipo de exceção ao tentar instanciar a classe.
    private ClasseProtegida obj = new ClasseProtegida();
}

Is this kind of protection possible?

Grateful.

Answer:

You can make internal members visible to another specific assembly using the InternalsVisibleToAttribute attribute. Obviously, you would have to change the declarations you want to share with the other specific assembly from public to internal .

This is an assembly-level attribute.

Usage example (copy from MSDN website):

[assembly: InternalsVisibleTo("NomeDoAssemblyAmigo, PublicKey=002400000480000094" + 
                              "0000000602000000240000525341310004000" +
                              "001000100bf8c25fcd44838d87e245ab35bf7" +
                              "3ba2615707feea295709559b3de903fb95a93" +
                              "3d2729967c3184a97d7b84c7547cd87e435b5" +
                              "6bdf8621bcb62b59c00c88bd83aa62c4fcdd4" +
                              "712da72eec2533dc00f8529c3a0bbb4103282" +
                              "f0d894d5f34e9f0103c473dce9f4b457a5dee" +
                              "fd8f920d8681ed6dfcb0a81e96bd9b176525a" +
                              "26e0b3")]

You can ignore the PublicKey parameter as I recall, but that could constitute a security hole as someone else could make an assembly with the specified name and use the methods.

Scroll to Top