Overview
PostSharp Laos allows aspect developers to validate that their aspect is being applied on the proper types, methods or fields.
Indeed, all aspects define a method named
CompileTimeValidate. The parameter of this method is
the type, method or field to which the aspect is being applied. By
overriding this method, aspect developers can check that the target
of the current aspect instance has expected characteristics, and
emitting a compile-time error if not.
The CompileTimeValidate method should return
true if the aspect has been applied on a valid target,
and false otherwise. If this method returned
false and no error was raised, the aspect will be
silently ignored.
Emitting a compile-time error
The easiest way to emit a compile-time error is to use the method MessageSource.MessageSink.Write:
MessageSource.MessageSink.Write( new Message( SeverityType.Error, "CU0001", "Cannot apply the Cache aspect to a method with arguments " + "passed by reference.", "MyAspectLibrary" ) );
If you plan to raise many messages, you may prefer to define
your own MessageSource. A
MessageSource is backed by a managed resource mapping
error codes to error messages.
In order to create your own MessageSource, you
should:
- Create a new managed resource. To each message will correspond a string item in the resource; the item name will be the message code, and the item value will be the formatting string of the error message.
- Create a static instance of the MessageSource class
for your message source:
internal static class MyMessageSource { public static readonly MessageSource Instance = new MessageSource( "MyWeaver", new ResourceManager( "MyWeaver.Messages", typeof(MyMessageSource).Assembly ) ); } - Then you can use a convenient set of methods on your
MessageSourceobject:MyMessageSource.Instance.Write( SeverityType.Error, "CU001", new object[] { type.FullName } );
Note that you can emit information and warning messages using
both mechanisms. Emitting a message does not affect the fact that
the aspect is applied or not. Only the return value of the
CompileTimeValidate method is relevant to this
regard.