/// <summary> /// takes a certain baseInterface and weaves an IAspectComponent Type /// the objects of this type are wrappers which add a certain functionality defined /// by the connected aspect(s) /// </summary> /// <param name="iface">interface to create wrapper for</param> /// <param name="additional">additional interfaces the aspect/object component should support</param> /// <returns>created Type</returns> public Type WeaveType(Type iface, Type[] additional) { // Create new type TypeCodeBuilder tcBuilder = codeBuilder.DefineType("Aspect" + iface.Name); // Params IDictionary fields = new Hashtable(); // add implementation for interface IAspectComponent ImplementAspectComponent(iface, tcBuilder, fields); // add implementation for interface iface ImplementInterface(iface, "OnMethodCall", tcBuilder, fields); // add additional interfaces if (additional != null) { foreach (Type t in additional) { ImplementInterface(t, "OnAdditionalMethodCall", tcBuilder, fields); } } // create type and save assembly Type aspectType = tcBuilder.TypeBuilder.CreateType(); return(aspectType); }
void ImplementInterface(Type baseInterface, string calledMethod, TypeCodeBuilder tcBuilder, IDictionary fields) { // Add Interface baseInterface TypeBuilder builder = tcBuilder.TypeBuilder; builder.AddInterfaceImplementation(baseInterface); // get methods from baseInterface and create wrapper methods MethodInfo[] methods = baseInterface.GetMethods(); foreach (MethodInfo m in methods) { ImplementMethod(m, calledMethod, fields, builder); } }
//--------------------------------------------------------------- #endregion //--------------------------------------------------------------- //--------------------------------------------------------------- #region Internal Helper Methods //--------------------------------------------------------------- void ImplementAspectComponent(Type baseInterface, TypeCodeBuilder tcBuilder, IDictionary fields) { // Add Interface IAspectComponent TypeBuilder builder = tcBuilder.TypeBuilder; builder.AddInterfaceImplementation(typeof(IAspectComponent)); // property baseInstance FieldBuilder fbBaseInstance = builder.DefineField("baseInstance", baseInterface, FieldAttributes.Private); tcBuilder.DefineStandardProperty("BaseInstance", fbBaseInstance, typeof(object), true, true, MethodAttributes.Public); fields["baseInstance"] = fbBaseInstance; // property aspect FieldBuilder fbAspect = builder.DefineField("aspectDispatcher", typeof(IAspectDispatcher), FieldAttributes.Private); tcBuilder.DefineStandardProperty("AspectDispatcher", fbAspect, typeof(IAspectDispatcher), true, true, MethodAttributes.Public); fields["aspectDispatcher"] = fbAspect; }