Pradeep Puranik
Pradeep Puranik

Reputation: 443

How to span C# namespaces over multiple assemblies?

A one-liner question does not make sense, so let me detail my challenge:

I have created 3 DLLs (MyUtils, MyConnector, MyAgent), each containing its own set of "internal" classes, types and members. All the classes, types and members are is their respective default namespace (same as their assembly name).

  1. MyAgent needs to add reference to MyConnector and use some of its classes. MyConnector needs to add reference to MyUtils and use some of it's classes. As it stands now, MyAgent may also need to access some types in MyUtils.

    Now, because of the fact that all types and members in MyUtils are internal, I am unable to add it as reference to MyConnector, and likewise from MyConnector to MyAgent. I do not want to make any of these types public because I do not want the application using my DLL to access them directly.

    I understand that theoretically it is possible to span a namespace over multiple assemblies, but not clear how to practically achieve the above scenario.

  2. Finally I want to deploy just MyAgent.dll to be used in an EXE. That EXE should have access only to the public types in MyAgent, with one exception: a MyConnection object (type contained in MyConnector) would be returned from a MyAgent method. Here again, my access specifier (internal) restricts this possibility.

I've been overthinking this so much that I'm now completely confused. Would appreciate some guidance from experienced programmers very much.

Thanks in advance.

Upvotes: 1

Views: 916

Answers (1)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

Spanning a namespace over multiple assemblies is done quite simple:

file1.cs in assembly 1:

namespace MyNamespace { ... }

file2.cs in assembly2:

namespace MyNamespace { ... }

However this won´t help you at all, as the intenal access-modifier will make your members visible to any class within the same assembly, regardless on their namespace. So even if you had two namespaces within assembly1, you could access all internal members declared in assembly1.MyNamespace, but not those within assembly2.MyNamespace.

So you have to make them public in order to access them from other assemblies. Alternativly you could also name a so-called "friend-assembly", that is able to access internal members from another assembly also. To do so, add an InternalsVisibleTo(fullNameForAssembly2) to your code.

Upvotes: 4

Related Questions