Why we use Dynamic Proxy

A dynamic proxy class is a class that implements a list of interfaces specified at runtime, so a method call through one of the interfaces on the class instance will be encoded and sent to another object through a single interface. It can be used to create a type of interface list safe for a proxy object without requiring a proxy class to be generated beforehand. Dynamic proxy classes are useful for an application or library that should provide a safe type of reflexive sending of pointers to objects that represent the interface APIs enter image description here

There is a good sample above the image, but why do we use a dynamic proxy?

Is there any simple example that is used in the real world for more perception?

+6
source share
4 answers

This link describes a dynamic proxy in code:

public static class DynamicProxyGenerator { public static T GetInstanceFor<T>() { Type typeOfT = typeof(T); var methodInfos = typeOfT.GetMethods(); AssemblyName assName = new AssemblyName("testAssembly"); var assBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assName, AssemblyBuilderAccess.RunAndSave); var moduleBuilder = assBuilder.DefineDynamicModule("testModule", "test.dll"); var typeBuilder = moduleBuilder.DefineType(typeOfT.Name + "Proxy", TypeAttributes.Public); typeBuilder.AddInterfaceImplementation(typeOfT); var ctorBuilder = typeBuilder.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, new Type[] { }); var ilGenerator = ctorBuilder.GetILGenerator(); ilGenerator.EmitWriteLine("Creating Proxy instance"); ilGenerator.Emit(OpCodes.Ret); foreach (var methodInfo in methodInfos) { var methodBuilder = typeBuilder.DefineMethod( methodInfo.Name, MethodAttributes.Public | MethodAttributes.Virtual, methodInfo.ReturnType, methodInfo.GetParameters().Select(p => p.GetType()).ToArray() ); var methodILGen = methodBuilder.GetILGenerator(); if (methodInfo.ReturnType == typeof(void)) { methodILGen.Emit(OpCodes.Ret); } else { if (methodInfo.ReturnType.IsValueType || methodInfo.ReturnType.IsEnum) { MethodInfo getMethod = typeof(Activator).GetMethod(/span>"CreateInstance",new Type[]{typeof((Type)}); LocalBuilder lb = methodILGen.DeclareLocal(methodInfo.ReturnType); methodILGen.Emit(OpCodes.Ldtoken, lb.LocalType); methodILGen.Emit(OpCodes.Call, typeofype).GetMethod("GetTypeFromHandle")); )); methodILGen.Emit(OpCodes.Callvirt, getMethod); methodILGen.Emit(OpCodes.Unbox_Any, lb.LocalType); } else { methodILGen.Emit(OpCodes.Ldnull); } methodILGen.Emit(OpCodes.Ret); } typeBuilder.DefineMethodOverride(methodBuilder, methodInfo); } Type constructedType = typeBuilder.CreateType(); var instance = Activator.CreateInstance(constructedType); return (T)instance; } } 
0
source

A common use case is Aspect Oriented Programming , in which you try to apply common functionality across several components without requiring the components themselves to implement the functionality. In these cases, you can use a dynamic proxy to migrate all targeting components with additional behavior. Doing this

A few examples:

  • ORMs such as Hibernate and Entity Framework do this to provide persistence around the first code. The main classes of the domain are built without any knowledge of their preservation, and frameworks either complete or extend these classes at startup to handle the actual implementation.

  • Combining all the elements of an interface with aspects such as logging or caching. For example, if you want to register every method call to ISomeInterface, you can write a dynamic proxy server that finds all the interface methods, calls the log method with the method data, and then passes the call to the actual implementation.

+3
source

Imagine that you have two objects: Car and Motorboat, which implement the CanDrive and CanFloat interfaces, respectively. Now you want to have a third object that implements both of these interfaces and that reuses the logic from Car and Motorboat. In languages ​​like Groovy, Ruby, and Scala, you can solve this using mixin. In Java, however, there is no such thing. Of course, you can use, for example. An adapter design pattern, but in many cases (especially when creating frameworks) a dynamic proxy will come in handy. Consider an example using the cglib library:

 CanDrive car = new Car(); CanFloat motorboat = new Motorboat(); net.sf.cglib.proxy.Mixin amphibian = net.sf.cglib.proxy.Mixin.create(new Object[] { car, motorboat }); TestCase.assertEquals("bzzz bzzz bzzz ...", ((CanFloat) amphibian)._float()); TestCase.assertEquals("pyr pyr pyr pyr ...", ((CanDrive) amphibian).drive()); 
+2
source
+1
source

Source: https://habr.com/ru/post/952176/


All Articles