Search code examples
c#postsharp

Validate class names in multiple projects at once using PostSharp


I have a solution with several API projects in various namespaces. I'm looking for a way to validate all the API projects at the same time, to check if any of them has a class (controller) with the same name as another class in any of those projects.

Let's say I have the following classes:

Api1.DogController
Api1.CatController

Api2.BirdController

Now somebody adds a new CatController to Api2 so we have

Api2.BirdController
Api2.CatController

I would like PostShart to throw a build error, because a class called CatController already exists in the Api1 project. And I'd prefer to avoid the need to add any attributes to classes that are supposed to be checked. I'm OK with referencing the constraint in AssemblyInfo file of API projects though.

I tried doing some stuff with ScalarConstraint and Types, like so:

[MulticastAttributeUsage(MulticastTargets.Class)]
    public class ControllerNamesValidation : ScalarConstraint
    {
        public override void ValidateCode(object target)
        {
            var targetType = (Type)target;

            //various experiments with targetType.GetMembers() or targetType.GetNestedTypes() here...
        }
     }

but failed.


Solution

  • PostSharp processes each project separately. It is possible to use ScalarConstraint to enforce your rule solution-wide at build time, but you would need to store the information about used controller names somewhere (e.g. the file system or the registry). This requires synchronization, which might add time to your compilation.

    If all of your API libraries are referenced by a single project, you might also achieve the same effect by targeting Assembly instead of Class, and then reflecting on the assembly in the constraint logic (see Assembly.GetReferencedAssemblies). You can filter the processed assemblies by the presence of the custom attribute.