Search code examples
postsharp

PostSharp C# - How to Implement All Fields Required


PostSharp contracts make it easy to label individual fields as Required. But I want a class attribute that makes all of the class fields required. I'm guessing I would have to implement a custom aspect to support this.

It seems like it would be a common need for anyone passing around data containers. Can anyone direct me to some code that implements a custom "AllFieldsRequired" aspect in PostSharp?


Solution

  • You can implement PostSharp.Aspects.IAspectProvider:

    public class AllFieldsRequiredAttribute : TypeLevelAspect, IAspectProvider
    {
        IEnumerable<AspectInstance> IAspectProvider.ProvideAspects(object targetElement)
        {
            Type type = (Type)targetElement;
            return type.GetFields().Select(
               m => new AspectInstance(m, new ObjectConstruction(typeof(RequiredAttribute))));
        }
    }
    
    [AllFieldsRequired]
    public class Foo
    {
        public string Bar;
        public object Baz;
    }