Possible Duplicate:
When should [assembly: InternalsVisibleTo()] be used?
Access to dll methods
I have two assemblies, A.dll and B.dll. A.dll has some common features, and B.dll uses it. I have to distribute A.dll and B.dll for other users eventually.
However, there are some methods in A.dll that I marked as public (for use by B.dll), but I don't want anyone else to use them.
Is there a good way to achieve this? Is the use of InternalsVisibleToAttribute
a good practice to achieve this?
Mark the items as internal in A.dll and add the following assembly property
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo( "B" )]
Be warned though, you can still access internal stuff through reflection so it's not 100% sealed.
InternalsVisibleTo
is the way to go.
The title of your question was a bit confusing at first, but after reading it was clear that what you want is to have some internal
(not public
) members accessible by a specific assembly.
The InternalsVisibleToAttribute
attribute is one way to do this but you have to realise that it exposes all internals to the other assembly.
Also note that if you're not using signed assemblies, the InternalsVisibleToAttribute
will allow access to internals from any assembly with that name. That may not be desirable.
Another option could be to use tooling to inject the required code from assembly "A" into assembly "B". That would allow "B" to function independently without accessing internals. It depends on how your assemblies are used whether that's a desirable solution or not.
Finally, you could access the code in assembly "A" using reflection. It's a bit fiddly but if there is just a couple of things you need it may be enough. This will also allow you to provide nice fallback or error handling when assembly "B" is present but A is missing.
As others have pointed out, reflection can provide access to anything in your assembly internal or not. If you need to protect your code you should look into obfuscation.