Search code examples
c#.netarchitectureencapsulation

How to hide common assembly classes?


I'm developing a piece of software that is split up into multiple projects, which you can think of as:

  • Client
  • Server
  • Common

Client and Server both reference Common, and use classes from it. For this reason, the classes in Common are public. However, although I want them to be used by Client and Server, I don't want them to be used by outside code that is using the Client and Server libraries.

Marking the classes as internal is clearly not an option. Is there a way I could make them available to Client and Server, but hide them from the outside world?


Solution

  • You disqualify internal since you assume your other Assemblies won't be able to use the internal Types, which is not necessarily true.

    InternalsVisibleToAttibute is an Assembly Attribute which allows you to make the internal Types of one projects visible to other selected projects.

    This way you can make the common types internal but use this Attribute to make them visible to Server and Client.

    [assembly:InternalsVisibleTo("Client", "PublicKey=2345456456...")]
    [assembly:InternalsVisibleTo("Server", "PublicKey=5345347366...")]
    

    In my opinion, internal is a generally a little bit of a code smell... It doesn't really protect your code as much as making it harder to be extended later... I would just keep the Types public and use the XML documents to assure that the one who uses my Types will use them as I meant them to be used, but that's just my point of view...