I've created a factory assembly that can process any type of transaction (that supports ITransactionType
). I can add more transaction types in separate assemblies, all of which will work with the factory without it needing to be recompiled (which is one of the benefits of a factory).
There is an actual list of transaction types that can be handled, so I've defined a static class with const strings, which is kept in a separate assembly. This is referenced by other assemblies to ensure consistent transaction type names. This assembly is not referenced by the factory, as it doesn't need to know, and it would result in unnecessary compilations of that project.
All this works just fine. I'll never reference the master list assembly in the factory project, because it know it doesn't make sense.
However, I'm concerned that if the project is being maintained by someone who doesn't understand all this, they may mistakenly add the reference to the master list assembly. Is there some way to prevent this refer开发者_高级运维ence from being added? IOW, if someone (perhaps even myself in the future) adds the reference, is there some way for me to force a compile error pointing to an explanation of why the behavior is unacceptable?
I can think of a few ways, though the language (.net, C#, vb) does not provide a specific method as far as I know:
- Use source control (you should, anyway), after compilation, unload the project from your solution (rightclick > unload), check in and mark as final, readonly or whatever to prevent further change.
- Add a little mini-script that does a pre-compilation step which checks for disallowed references (you can add it under project properties).
- Add a
#warning
to your source which is always issued: "should not be compiled with XXX", please make sure it's not in". - Use circular dependency against itself: add a reference to
Transaction
factory in your constants library, this will effectively prevent adding a reference the other way around. - A bit nastier: dynamically check for the existence of the reference from the
cctor
(the static constructor) using reflection and throw an exception if found. This will throw a hard exception (but only on any test) if anybody ever attempts to add a reference to this lib. - Perhaps more basic: in your nUnit tests (or whatever test framework you use), simply add one test:
MustNotReferenceXXX
and in its body, dynamically check whether the lib is referenced.
I'll update if I can think of anything easier, though I think points 5 and 6 are easiest to implement and future proof.
You can use the following:
Assembly.GetExecutingAssembly()
.GetReferencedAssemblies()
.Select( a => a.Name )
to get the names of all assemblies referenced by the currently executing assembly. Then, you can check whether this list of names contains the assembly that you do not want to be referenced.
For details, see https://stackoverflow.com/a/72460117/773113
精彩评论