Post on 23-Feb-2016
description
transcript
AOP via Policy Injection & Unity Application BlocksDmitri Nesterukdmitri@activemesa.comhttp://activemesa.com http://spbalt.net
AgendaAOP and Policy Injection
AOP overviewThe world of proxiesPolicy Injection AB
Unity interceptionInterceptor extensionCustom attributes
AOP and Policy InjectionPart I
Aspect-Oriented Programming
Separation of functional and non-functional requirements
Without mixing code
→
Ways of adding AOPPost-build assembly modification
PostSharpMetaprogramming
BooNemerle
ProxiesSpring.netCastlePolicy Injection AB
compilerextension
ProxyA proxy is a substitute object
It has both the original functionalityAnd the AOP-added features
Can take an existing object and intercept property access, method calls, etc.Must (typically) use an interface
That way, implementation can be transparently substituted
What is PIAB?Part of Enterprise Libraryhttp://entlib.codeplex.comAllows you to intercept calls to an object
MethodProperty Get/Set
Lets you set up a handler pipeline
Is PIAB an AOP framework?[…] However, the Policy Injection Application Block is not an AOP framework implementation for the following reasons:
It uses interception to enable only pre-processing handlers and post-processing handlers.It does not insert code into methods.It does not provide interception for class constructors.
Policy Injection Application Block, MSDNhttp://msdn.microsoft.com/en-us/library/cc511729.aspx
How does it work?By default, PIAB uses transparent proxies
Used in remotingTo create a proxy for your class, it must
Either implement a well-known interface; orDerive from MarshalByRefObject
PIAB uses a factory to create objectsJust like Unity!
Scenariopublic interface IPerson{ int Age { get; set; } string FirstName { get; set; } string LastName { get; set; } string GetInfo();}
public class Person : IPerson{ public Person(int age, string firstName, string lastName) { Age = age; FirstName = firstName; LastName = lastName; } public string GetInfo() { return FirstName + " " + LastName + " is " + Age + " years old."; }}
Object creation (no aspects yet!)
Concrete typesOnly if object derived from MarshalByRefObjectvar p = PolicyInjection.Create<Person>(…);Will fail otherwise
Interface typesvar p = PolicyInjection.Create<Person, IPerson>( 27, "Dmitri", "Nesteruk");
Can apply to existing objectPerson p = new Person(27, "Dmitri", "Nesteruk");IPerson wp = PolicyInjection.Wrap<IPerson>(p);
Applying policiesA policy needs to specify
Where it needs to be applied (matching rules)What needs to be done (handler)
EntLib provides several ‘stock’ handlers
ExampleIn each property assignmentCheck that the value is not null
And throw ArgumentException if it is
Typically edited in designer
Stock handlersPIAB comes pre-packaged with several ‘stock’ handlers
These handlers integrate with other application blocks
Can always write your own
Including a designer
AuthorizationCachingCustomException handling
LoggingPerformanceValidation
Custom validation policyDemo
Custom handler creationImplement ICallHandlerImplement Invoke() to
Do your own pre/postprocessingTo invoke next item in chain, usereturn getNext()(input, getNext);
Make sure to tag handler class with[ConfigurationElementType( typeof(CustomCallHandlerData))]Create your custom policy
Warning: sign the assembly; orEdit config manually
ICallHandler is defined in Unity
AB
Unity InterceptionPart II
Unity Object ResolutionUnity is capable of giving us predefined object instances
IPerson p = uc.Resolve<IPerson>();IPerson can resolve to a predefined type, but it doesn’t have to!
It can resolve instead to a type constructed at runtimeThis type can use the functionality of Person and enhance it
Unity & PIABBoth Unity and PIAB give out objects
Unity resolves dependenciesPIAB creates proxies
Synergy? Absolutely.In Unity, we can decide whether or not a proxy needs to be createdThen we can selectively apply PIABAnd yield an object conforming to an interface
Interoperation between Unity and PIAB is possible, but…
There is an alternative
Unity Interception ExtensionSince v1.2, Unity has a…
Microsoft.Practices.Unity.InterceptionExtension
Works just like PIAB, butEasy to configure in codeIntegrates with Unity container
ArtefactsCall handler (as per PIAB)Handler attribute – used to decorate elements it affectsUnity extension configuration
Interceptor implementationDerive from HandlerAttribute
Override CreateHandler()
Make a handler that implements ICallHandler
Define Invoke()Use getNext().Invoke() to call decorated methodAdd code around it as necessary
Add and configure interceptionuc.AddNewExtension<Interception>();uc.Configure<Interception>() .SetInterceptorFor<IPerson>( new TransparentProxyInterceptor());
Unity InterceptionDemo
ConclusionsPIAB is useful for ‘stock’ interceptionUnity is useful for general-purpose interceptionUnity is positioned to supersede PIAB for AOPBest for dynamic reconfiguration
Use precompilation for speed
LinksAOP frameworks to try
PostSharp http://postsharp.org Our webcast at http://www.techdays.ru/videos/1320.html Spring.net http://www.springframework.net/Castle http://www.castleproject.org Enterprise library http://entlib.codeplex.com
albvobqllkutmywmwreerqqmqiqdnwgsswda
vpdvnuxjlsytubnbycthrryuvastadtnzffx
gqhbjjpyowsigiciigsofnfrjfdcfgmkwuyj
vbvemitijxuvwsjuguylbocmykubwswnpxio
kaycqosunkscgxjxjeqphjiacmjzhckvxkak
fecruuxqppkofwgxbvjmbeleewkscvnnogcz
wwfwinehjqlhxuvjomhgsxajzbdnuascnaji
xwinwzjdspnwipcndsrmjhzqjgbwjmezkjva
zouqwdcjcfoxwthvsrhomjynauppuphznsjr
mbzowkinthlikzwmzmfxchomwxbsmxucjxos
hxuetpuxeovlhaypffvaxzxlzulclnqgegmx
ykkkqjnhpijwipddaxzszempclimsugeizom
qprpdwmyqtovmpTHEyENDvzdczxmgqqrhnbjibqipxnhwidohmawcxmghcyriknpndmcxlze
hhsclfsylkjsptdqebkvuxkmkzpgkenafhhr
oxvwkujutneuqfadnedyyyfczcapxyfbrwey
ofavfhzryanzuqrognfpxljyluanrdorvkmf
jynhpcctkxytbfjrnxgczhspceiqgxkpfgrn
lyiiftisbifckcheslwysupdvxbrlqlkizdz
wsawriiumnixrcjndhnwgsfsilhabhlhxmvp
tegknoisgsxvbokecijybedrtpexvrcwuvds
doazttmuiuvubplwcpxnkkvaavbbseefdbfy
ivcjkrgrytjamfvhbfsbzlinaxclrlzivlcb
nudllguyrttuqtlyjlquhaouoptgvlqqrkrqyplzdxnqnqvtfbuhrynkfqithiuwinmloccc