6. AOP
“ In computing, aspect-oriented programming (AOP) is
a programming paradigm which aims to increase modularity by
allowing the separation of cross-cutting concerns. “
wikipedia
9. Aspectos Base
• AssemblyLevelAspect
– classe base para todos os aspectos aplicados a assemblies
• TypeLevelAspect
– classe base para todos os aspectos aplicados a tipos
• MethodLevelAspect
– classe base para todos os aspectos aplicados a métodos
• LocationLevelAspect
– Classe base de todos os aspectos aplicados a campos ou
parâmetros de métodos
• EventLevelAspect
– classe base para todos os aspectos aplicados a eventos
10. Aspectos Multicast
– MulticastAttributes:
• visibility,
• virtuality,
• implementation,
• scope.
– AttributeTargetTypes:
• Nome Completo
• Wildmask
• RegularExpressions
– AttributePriority : Valor da prioridade de aplicação do
aspecto, quanto mais baixo o valor mais prioritário
13. Pós-Compilação
MSIL Injection
CompileTimeInitialize
Inicialização em compile
time CompileTimeValidate
RunTimeInitialize
Inicialização em runtime
14. Pós-Compilação
1. Obter a metadata do módulo.
2. Traduzir as instruções IL para um formato
relevante para o processo de weave
conseguir interpretar.
3. Detectar os Joinpoints ( code weaver task ).
4. Tratamento explicito para os Aspectos
associados ao tratamento de excepções.
5. Injectar as instruções IL dos advices.
6. Voltar a compilar de novo o modulo.
15. Tempo de vida
Tempo de vida igual ao da aplicação
Static Scoped Aspect
Por Default !
At Compile Time
Tempo de vida igual ao da instância
Instance Scoped Aspect
alvo
At runtime • IInstanceScopedAspect
•InstanceLevelAspect
17. Conclusões
• Agnostico à linguagem de programação
• MSIL Injection
• Facil utilização
• Aplicação a todos os tipos de join
points do .NET
• Codigo gerado – dificil leitura
21. Próximas reuniões presenciais
• 26-05-2012 – Maio
• 02-06-2012 – Junho (Coimbra)
• 16-06-2012 – Junho
• 21-07-2012 – Julho
Reserva estes dias na agenda! :)
separation o cross cutting concernsaspectadvice PointcutJoinpointsweavingAspect: definição do aspectAdvice: definição do que é que se pretende executarJoinpoints: locais onde se injecta o codigo do advice do aspectoPointcut: joinpoints[]
Adicionar o aspecto ao assembly e ver a aplicação a estoirar ! Stack overflow !! We can't build the project because PostSharp is trying to apply our aspect to our aspect. The result of this, at least in this case, would be a stack overflowAttributeTargetTypes ( string onde se preenche o nomecompleto to tipo )
[MulticastAttributeUsage(MulticastTargets.Field | MulticastTargets.Property, TargetMemberAttributes = MulticastAttributes.Public | MulticastAttributes.Instance)] public sealed class AddXmlIgnoreAttribute : MethodLevelAspect, IAspectProvider{ private static readonlyCustomAttributeIntroductionAspectcustomAttributeIntroductionAspect = new CustomAttributeIntroductionAspect( new ObjectConstruction(typeof(XmlIgnoreAttribute).GetConstructor(Type.EmptyTypes))); public IEnumerable<AspectInstance> ProvideAspects(object targetElement) { MemberInfomemberInfo = (MemberInfo)targetElement; if (memberInfo.IsDefined(typeof(XmlElementAttribute), false) || memberInfo.IsDefined(typeof(XmlAttributeAttribute), false)) yield break; yield return new AspectInstance(targetElement, customAttributeIntroductionAspect); }}
Referenciar um projecto com postsharpMostrar o assembly e espaço de nomesCriar um aspecto OnMethodBoundoryAspectMostrar os métodos que podemos fazer overrideParametrosCompilar – Alertar para o popup do executavel que fez as coisas... Mostrar o ILSpy
Compile time weavingLet the standard compiler do its job, then read the compiled assembly, modify it and write it back. This is the approach of PostSharp.msBuild: MSBUILD: Este ficheiro : C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\Microsoft.Common.targetsDa indicação que deve ser carregado o ficheiro : c:\\Program Files\\MSBuild\\v2.0\\Custom.After.Microsoft.Common.targetsFicheiro este que é alterado pelos executaveis que pretendem executar tarefas após o build. O Post sharp edita-o com a informação das tarefas a executar após o build
Para os aspectos normais : Aspect for each targetPara os aspectos que implementem IInstanceScopedAspect,Return this.MemberwiseClone()nainvocação do CreateInstance(AdviceArgsadviceArgs) da interface IInstanceScopedAspect
The reasons why I chose post-compilation when designing PostSharp 5 years ago are:Language agnosticism.MSIL has stabler specifications compared to high-level languages (which have non-trivial updates every second year).Most of the time, MSIL is the level of abstraction you need when dealing with aspects. You don't need to know all the equivalent constructs (think f 'using' and 'try-finally').Before 2008, nobody has succeeded in producing a decent C# compiler. The difficulties met by Mono were impressive enough, even if they have caught up now.Dealing with binary seemed much faster than dealing with source code.Dealing with a binary assembly makes it possible to execute it -- the assembly being processed can transforme itself. It was unheard before PostSharp Laos was first released.