Created
December 23, 2015 01:38
-
-
Save jeremybeavon/e0e852da05f2e239c189 to your computer and use it in GitHub Desktop.
Generate a Castle proxy for every type in a assembly and save the proxy assembly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.IO; | |
| using System.Linq; | |
| using System.Reflection; | |
| using Castle.DynamicProxy; | |
| private static void BuildProxyAssembly(string assemblyPath) | |
| { | |
| string assemblyName = Path.GetFileNameWithoutExtension(assemblyPath) + ".Proxies"; | |
| string modulePath = Path.Combine(Path.GetDirectoryName(assemblyPath), assemblyName + ".dll"); | |
| DefaultProxyBuilder proxyBuilder = new DefaultProxyBuilder(new ModuleScope(true, true, assemblyName, modulePath, assemblyName, modulePath)); | |
| Assembly assembly = Assembly.LoadFrom(assemblyPath); | |
| var types = from classType in assembly.GetTypes() | |
| where classType.IsClass && !classType.ContainsGenericParameters && !classType.IsAbstract && classType.IsPublic | |
| from interfaceType in classType.GetInterfaces() | |
| where interfaceType.IsPublic && classType.Assembly == interfaceType.Assembly && IsInterfaceOnlyOnClass(classType, interfaceType) | |
| select new { ClassType = classType, InterfaceType = interfaceType }; | |
| var typeArray = types.ToArray(); | |
| Console.WriteLine("Total: {0}", typeArray.Length); | |
| int count = 0; | |
| var options = new ProxyGenerationOptions(); | |
| foreach (var type in typeArray) | |
| { | |
| count++; | |
| proxyBuilder.CreateInterfaceProxyTypeWithTarget(type.InterfaceType, null, type.ClassType, options); | |
| Console.WriteLine("{0}: {1}", count, type.ClassType.FullName); | |
| } | |
| Console.WriteLine(count); | |
| proxyBuilder.ModuleScope.SaveAssembly(); | |
| } | |
| private static bool IsInterfaceOnlyOnClass(Type classType, Type interfaceType) | |
| { | |
| for (Type baseType = classType.BaseType; baseType != null && baseType.Assembly == classType.Assembly; baseType = baseType.BaseType) | |
| if (baseType.GetInterfaces().Contains(interfaceType)) | |
| return false; | |
| return !classType.GetInterfaces().Any(type => type != interfaceType && type.Assembly == classType.Assembly && type.IsAssignableFrom(interfaceType)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment