|
| 1 | +# Any Processor |
| 2 | +Easily write an ILPostProcessor with `AnyProcessor` |
| 3 | + |
| 4 | +``` c# |
| 5 | +public class WeavingAttribute : Attribute {} |
| 6 | + |
| 7 | +[Weaving] |
| 8 | +public class Foo |
| 9 | +{ |
| 10 | + [Weaving] |
| 11 | + public int Value; |
| 12 | +} |
| 13 | + |
| 14 | +public class WeavingPostProcessor : ILPostProcessor |
| 15 | +{ |
| 16 | + public override ILPostProcessor GetInstance() |
| 17 | + { |
| 18 | + return this; |
| 19 | + } |
| 20 | + |
| 21 | + public override bool WillProcess(ICompiledAssembly compiledAssembly) |
| 22 | + { |
| 23 | + return AnyProcessor<WeavingAttribute>.WillProcess(GetType(), compiledAssembly.Name, compiledAssembly.References); |
| 24 | + } |
| 25 | + |
| 26 | + public override ILPostProcessResult Process(ICompiledAssembly compiledAssembly) |
| 27 | + { |
| 28 | + var assemblyMemory = compiledAssembly.InMemoryAssembly; |
| 29 | + using var processor = new AnyProcessor<WeavingAttribute>(assemblyMemory.PeData, assemblyMemory.PdbData, compiledAssembly.References); |
| 30 | + processor.ProcessType += OnProcessType; |
| 31 | + processor.ProcessField += OnProcessField; |
| 32 | + var (pe, pdb) = processor.Process(); |
| 33 | + var warnings = processor.Logger.Warnings.Select(msg => new DiagnosticMessage { DiagnosticType = DiagnosticType.Warning, MessageData = msg }); |
| 34 | + var errors = processor.Logger.Errors.Select(msg => new DiagnosticMessage { DiagnosticType = DiagnosticType.Error, MessageData = msg }); |
| 35 | + var messages = warnings.Concat(errors).ToList(); |
| 36 | + return pe == null ? new ILPostProcessResult(null, messages) : new ILPostProcessResult(new InMemoryAssembly(pe, pdb), messages); |
| 37 | + |
| 38 | + bool OnProcessType(TypeDefinition type, CustomAttribute attribute) |
| 39 | + { |
| 40 | + // weaving type with `WeavingAttribute` |
| 41 | + // here should be class `Foo` |
| 42 | + } |
| 43 | + |
| 44 | + bool OnProcessField(FieldDefinition field, CustomAttribute attribute) |
| 45 | + { |
| 46 | + // weaving field with `WeavingAttribute` |
| 47 | + // here should be field `Foo.Value` |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | +``` |
0 commit comments