How do I prevent my .Net dll from being added as a

2019-04-10 12:45发布

问题:

Say I've written a .Net dll and want to distribute it with my application. How can I prevent any user with the savvy to install a copy of VS from adding a reference to this dll to their own applications?

回答1:

There is no way to prevent a user from adding a reference. It's a passive action from the part of your DLL and there is nothing you can do to prevent it from occuring.

What you can do though, is make adding a reference a non-worthwhile operation. For instance, if all types in the DLL were internal or private, it take more than simply adding a reference for users to use the types in the DLL. Furthmore, obfuscating the DLL would make it even harder.



回答2:

You cannot prevent someone from adding a reference to your dll. What you can do however is to make it hard for them to use it if they do add a reference.

Code Access Security (CAS) can be used to prevent unauthorised code for calling into an assembly, but this has an effect on the performance of calls, and is overkill for this purpose.

Another approach would be to mark everything in the dll as internal. If you have other assemblies that need access to the classes in the dll, make them friend assemblies using the InteralsVisibleTo attribute. This allows other assemblies to access to the internal classes of your dll. Tie this together with signed assemblies (to use with the InternalsVisibleTo definitions) and it should be enough.



回答3:

you might find "StrongNameIdentityPermission" class helpful

http://msdn.microsoft.com/en-us/library/system.security.permissions.strongnameidentitypermission.aspx



回答4:

I seriously doubt this is possible. Even if it were, an assembly with full thrust can fake all evidence and pretend to be your program.



回答5:

Although .NET does not allow true static linking, you may be able to fake it, packaging your dll and exe into one assembly. Here is a tool that can do this: ILMerge There may be others.



回答6:

You could obfuscate the DLL (Tools -> Dotfuscator Community Edition) to make it unworthwile to reference your DLL.