static void Main(string[] args) { IDynamicFactory factory = DynamicAssemblyBuilder.CreateDynamic("Test"); var t = factory.CreateInterfaceProxy("test"); Type ikkType = typeof(IKk); var gg = ikkType.GetGenericArguments(); Type aspect = typeof(DefaultAspectAttribute); var c = new CustomAttributeBuilder(aspect.GetConstructors()[0], new object[0]); t.TypeFactory.TypeBuilder.SetCustomAttribute(c); t.TypeFactory.AddInterface(ikkType); var field = t.BuildField("target", typeof(IKk), FieldAttributes.Private); var type = t.BuildField("type", typeof(Type), FieldAttributes.Private); var proxyConstructor = t.ProxyConstructor(field, type); proxyConstructor.SetConstructor(null); var pm = t.ProxyMethod(field, ikkType.GetMethods()[0], type); pm.SetProxyMethod(ikkType.GetMethods()[0], ikkType); Type finish = t.Finish(); var k = new Program(8, 9); IKk dist = (IKk)Activator.CreateInstance(finish, k, typeof(IKk)); dist.TestBB(1, 20); }
static TinyMapper() { IDynamicAssembly assembly = DynamicAssemblyBuilder.Get(); _targetMapperBuilder = new TargetMapperBuilder(assembly); _config = new TinyMapperConfig(_targetMapperBuilder); }
/// <summary> /// 使用扩展属性对架构类进行包装。 /// </summary> /// <param name="schemaType">架构类。</param> /// <param name="properties">扩展的属性列表。</param> /// <returns></returns> private static Type BuildWrapType(Type schemaType, PropertyInfo[] properties) { var dyAssemblyBuilder = new DynamicAssemblyBuilder("SchemaExtension_" + schemaType.Name); var dyTypeBuilder = dyAssemblyBuilder.DefineType(schemaType.Name, baseType: schemaType); foreach (var property in properties) { var defaultValue = GetPropertyDefaultValue(property); var dyPropertyBuilder = dyTypeBuilder.DefineProperty(property.Name, property.PropertyType); dyPropertyBuilder.DefineGetSetMethods(); SetPropertyCustomAttributes(property, dyPropertyBuilder); } foreach (var con in schemaType.GetConstructors()) { var parameters = con.GetParameters(); var dyConsBuilder = dyTypeBuilder.DefineConstructor(parameters.Select(s => s.ParameterType).ToArray(), ilCoding: (b) => { b.Emitter .ldarg_0 .For(1, parameters.Length + 1, (e, i) => e.ldarg(i)) .call(con).ret(); }); } return(dyTypeBuilder.CreateType()); }
/// <summary> /// 初始化 <see cref="EntityTypeBuilder"/> 类的新实例。 /// </summary> /// <param name="typeName">动态类的类型名称。</param> /// <param name="assemblyBuilder">一个 <see cref="DynamicAssemblyBuilder"/> 容器。</param> /// <param name="baseType">所要继承的抽象类型,默认为 <see cref="EntityObject"/> 类。</param> public EntityTypeBuilder(string typeName, DynamicAssemblyBuilder assemblyBuilder = null, Type baseType = null) { TypeName = typeName; this.assemblyBuilder = assemblyBuilder ?? new DynamicAssemblyBuilder("<DynamicType>_" + typeName); InnerBuilder = this.assemblyBuilder.DefineType(TypeName, baseType: baseType ?? typeof(EntityObject)); EntityType = InnerBuilder.UnderlyingSystemType; Properties = new List <IProperty>(); }
public void SaveTest() { var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dynamicAssembly1.dll"); var assemblyBuilder = new DynamicAssemblyBuilder("dynamicAssembly1", fileName); assemblyBuilder.Save(); Assert.IsTrue(File.Exists(fileName)); }
public void SaveAllTest() { var assemblyBuilder = new DynamicAssemblyBuilder("dynamicAssembly1"); var type1 = assemblyBuilder.DefineType("class1"); var type2 = assemblyBuilder.DefineType("class2"); assemblyBuilder.Save(); Assert.AreEqual(2, assemblyBuilder.AssemblyBuilder.GetTypes().Length); }
public void TestSaveAll() { var assemblyBuilder = new DynamicAssemblyBuilder("dynamicAssembly1"); var type1 = assemblyBuilder.DefineType("class1"); var type2 = assemblyBuilder.DefineType("class2"); #if NETAPPCORE assemblyBuilder.Save(); #endif Assert.AreEqual(2, assemblyBuilder.AssemblyBuilder.GetTypes().Length); }
public void TestAssemblyBuilder() { var assemblyBuilder = new DynamicAssemblyBuilder("DynamicAssembly1"); var interfaceBuilder = assemblyBuilder.DefineInterface("IInterface"); var typeBuilder = assemblyBuilder.DefineType("Class1"); var enumBuilder = assemblyBuilder.DefineEnum("Enum1"); var assembly = assemblyBuilder.Save(); Assert.AreEqual("Class1", typeBuilder.TypeBuilder.Name); Assert.AreEqual("DynamicAssembly1", assembly.GetExportedTypes().Length); }
public void TestBuild() { #if !NETCOREAPP2_0 var assBuilder = new DynamicAssemblyBuilder("test_dll", "e:\\test.dll"); var typeBuilder = new EntityTypeBuilder("TestEntity", assBuilder); #else var typeBuilder = new EntityTypeBuilder("testclass"); #endif var pName = new GeneralProperty() { Name = "Name", Info = new PropertyMapInfo { FieldName = "name" }, Type = typeof(string) }; typeBuilder.Properties.Add(pName); typeBuilder.Properties.Add(new GeneralProperty() { Name = "Age", Info = new PropertyMapInfo { FieldName = "age" }, Type = typeof(int?) }); typeBuilder.Properties.Add(new GeneralProperty() { Name = "Sex", Info = new PropertyMapInfo { FieldName = "sex" }, Type = typeof(Sex) }); typeBuilder.DefineValidateRule(pName, () => new System.ComponentModel.DataAnnotations.MaxLengthAttribute(15)); var type = typeBuilder.Create(); #if !NETCOREAPP2_0 assBuilder.Save(); #endif var e = type.New <IEntity>(); e.SetValue("Name", "fireasy"); e.SetValue("Age", 12); e.SetValue("Sex", Sex.M); Assert.AreEqual(e.GetValue("Name"), "fireasy"); Assert.AreEqual(e.GetValue("Age"), 12); Assert.AreEqual(e.GetValue("Sex"), Sex.M); ValidationUnity.Validate(e); var property = PropertyUnity.GetProperty(type, "Name"); Assert.IsNotNull(property); Assert.AreEqual(type.GetProperty("Name").GetValue(e), "fireasy"); }
public TinyMapper(IEnumerable <IObjectMapperBuilder> builders) { this._lock = new object(); _mappers = new Dictionary <TypePair, Mapper>(); IDynamicAssembly assembly = DynamicAssemblyBuilder.Get(); _targetMapperBuilder = new TargetMapperBuilder(assembly); _config = new TinyMapperConfig(_targetMapperBuilder); foreach (var builder in builders) { builder.Build(this); } }
private static Type InternalBuildImplementType(Type definedType) { var assemblyBuilder = new DynamicAssemblyBuilder("ImplAssembly"); var typeBuilder = assemblyBuilder.DefineType(definedType.Name + "_Impl"); if (definedType.IsInterface) { typeBuilder.ImplementInterface(definedType); } else { typeBuilder.BaseType = definedType; } //实现属性 foreach (var property in definedType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var getMethod = property.GetGetMethod(); var setMethod = property.GetSetMethod(); if (definedType.IsInterface || (getMethod != null && getMethod.IsVirtual) || (setMethod != null && setMethod.IsVirtual)) { var propertyBuilder = typeBuilder.DefineProperty(property.Name, property.PropertyType); if (getMethod != null) { propertyBuilder.DefineGetMethod(); } if (setMethod != null) { propertyBuilder.DefineSetMethod(); } } } //实现方法 foreach (var method in definedType.GetMethods(BindingFlags.Public | BindingFlags.Instance)) { if ((definedType.IsInterface || method.IsVirtual) && !Regex.IsMatch(method.Name, @"^set_|get_")) { var parameters = method.GetParameters(); var methodBuilder = typeBuilder.DefineMethod(method.Name, method.ReturnType, parameters.Select(s => s.ParameterType).ToArray()); foreach (var par in parameters) { methodBuilder.DefineParameter(par.Name, par.IsOut, par.DefaultValue != DBNull.Value, par.DefaultValue); } } } return(typeBuilder.CreateType()); }
public static Assembly CompileAll(Assembly assembly, IInjectionProvider injection) { return(cache.GetOrAdd(assembly.FullName, () => { var assemblyName = string.Concat(assembly.GetName().Name, "_Dynamic"); var assemblyBuilder = new DynamicAssemblyBuilder(assemblyName); assembly.GetExportedTypes() .Where(s => s.IsNotCompiled()) .ForEach(s => EntityProxyBuilder.BuildType(s, null, assemblyBuilder, injection)); return assemblyBuilder.AssemblyBuilder; })); }
private static Assembly GetAssemblyFromCache(Assembly assembly) { var lazy = new Lazy <Assembly>(() => { var assemblyName = string.Concat(assembly.GetName().Name, "_Dynamic"); var assemblyBuilder = new DynamicAssemblyBuilder(assemblyName); assembly.GetExportedTypes() .Where(s => s.IsNotCompiled()) .ForEach(s => EntityProxyBuilder.BuildType(s, null, assemblyBuilder)); return(assemblyBuilder.AssemblyBuilder); }); return(cache.GetOrAdd(assembly.FullName, t => lazy.Value)); }
private static Type BuildProfileProxyType(Type profileType, List <string> assemblyList) { var fileName = Util.GenerateTempFileName(); assemblyList.Add(fileName); var assemblyBuilder = new DynamicAssemblyBuilder("__Profile_Proxy", fileName); var typeBuilder = assemblyBuilder.DefineType("Profile", baseType: typeof(MarshalByRefObject)); //定义Table代理类的属性 foreach (var property in profileType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { typeBuilder.DefineProperty(property.Name, property.PropertyType).DefineGetSetMethods(); } assemblyBuilder.Save(); return(typeBuilder.UnderlyingSystemType); }
/// <summary> /// 使用扩展属性对架构类进行包装。 /// </summary> /// <param name="schemaType">架构类。</param> /// <param name="properties">扩展的属性列表。</param> /// <returns></returns> private static Type BuildWrapType(PropertyInfo[] properties) { var dyAssemblyBuilder = new DynamicAssemblyBuilder("ProfileExtension"); var dyTypeBuilder = dyAssemblyBuilder.DefineType("ProfileEx", baseType: typeof(Profile)); foreach (var property in properties) { var defaultValue = GetPropertyDefaultValue(property); var dyPropertyBuilder = dyTypeBuilder.DefineProperty(property.Name, property.PropertyType); dyPropertyBuilder.DefineGetSetMethods(); SetPropertyCustomAttributes(property, dyPropertyBuilder); } var wrapType = dyTypeBuilder.CreateType(); propertyCache = wrapType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(s => new PropertyMap(s)).ToList(); return(wrapType); }
private static ProxyType BuildSchemaProxyType(List <string> assemblyList) { var proxyType = new ProxyType(); var fileName = Util.GenerateTempFileName(); assemblyList.Add(fileName); var assemblyBuilder = new DynamicAssemblyBuilder("__Schema_Proxy", fileName); var tableTypeBuilder = assemblyBuilder.DefineType("Table", baseType: typeof(MarshalByRefObject)); var columnTypeBuilder = assemblyBuilder.DefineType("Column", baseType: typeof(MarshalByRefObject)); var referenceTypeBuilder = assemblyBuilder.DefineType("Reference", baseType: typeof(MarshalByRefObject)); tableTypeBuilder.ImplementInterface(typeof(_IIdentity)); columnTypeBuilder.ImplementInterface(typeof(_IIdentity)); referenceTypeBuilder.ImplementInterface(typeof(_IIdentity)); proxyType.TableType = tableTypeBuilder.UnderlyingSystemType; proxyType.ColumnType = columnTypeBuilder.UnderlyingSystemType; proxyType.ReferenceType = referenceTypeBuilder.UnderlyingSystemType; //定义Table代理类的属性 foreach (var property in SchemaExtensionManager.GetWrapType <Table>().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var propertyType = Replace(property.PropertyType, proxyType); tableTypeBuilder.DefineProperty(property.Name, propertyType).DefineGetSetMethods(); } //定义Table代理类的属性 foreach (var property in SchemaExtensionManager.GetWrapType <Column>().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var propertyType = Replace(property.PropertyType, proxyType); columnTypeBuilder.DefineProperty(property.Name, propertyType).DefineGetSetMethods(); } //定义Table代理类的属性 foreach (var property in SchemaExtensionManager.GetWrapType <Reference>().GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var propertyType = Replace(property.PropertyType, proxyType); referenceTypeBuilder.DefineProperty(property.Name, propertyType).DefineGetSetMethods(); } assemblyBuilder.Save(); return(proxyType); }
static IEnumerable <Type> CreateEntitiesTypes(DbConnection existingConnection) { using (MetadataInitializationContext context = new MetadataInitializationContext(existingConnection, false)) { DynamicAssemblyBuilder assemblyBuilder = new DynamicAssemblyBuilder(); var entities = context.Entities.Include(c => c.Attributes) .Include(c => c.Listeners) .Include(c => c.Proxies) .Include("Attributes.Type") .Include(c => c.ManyToOneRelationships) .Include(c => c.OneToManyRelationships).ToArray(); var types = assemblyBuilder.BuildTypes(entities).ToArray(); assemblyBuilder.SaveAssembly(); return(types); } }
/// <summary> /// 编译程序集中的所有类型。 /// </summary> /// <param name="contextType">当前上下文实例的类型。</param> /// <param name="assembly">当前的程序集。</param> /// <param name="types">指定需要编译的类型,如果为 null 则遍列 <paramref name="assembly"/> 中的所有可导出类型。</param> /// <param name="injection">用来向实体类中注入代码。</param> /// <returns></returns> public static Assembly CompileAll(Type contextType, Assembly assembly, Type[] types, IInjectionProvider injection) { var assemblyKey = new EntityAssemblyKey { ContextType = contextType, Assembly = assembly }; return(_cache.GetOrAdd(assemblyKey, key => { var rndNo = RandomGenerator.Create(); var assemblyName = string.Concat(key.Assembly.GetName().Name, ".", rndNo); var assemblyBuilder = new DynamicAssemblyBuilder(assemblyName); types ??= key.Assembly.GetExportedTypes(); types.Where(s => s.IsNotCompiled() && !s.IsSealed) .ForEach(s => EntityProxyBuilder.BuildType(s, null, assemblyBuilder, injection)); return assemblyBuilder.AssemblyBuilder; })); }
/// <summary> /// 初始化 <see cref="EntityContext"/> 对象中的所有实体类型的代理。 /// </summary> /// <param name="contextType"></param> /// <param name="entityTypes"></param> public static void CompileContextTypes(Type contextType, Type[] entityTypes) { //查找未实现的AOP类型 entityTypes = entityTypes.Where(s => s.IsNotImplAOPType()).ToArray(); if (entityTypes.Length == 0) { return; } lock (locker) { var assemblyBuilder = new DynamicAssemblyBuilder(contextType.FullName + "_Proxy"); var option = new InterceptBuildOption { AssemblyBuilder = assemblyBuilder, TypeNameFormatter = "{0}_Proxy" }; foreach (var type in entityTypes) { proxyTypes.TryAdd(type, InterceptBuilder.BuildType(type, option)); } } }
private Type MakeTypeImplementing(Type interfaceType, bool isFuzzy) { if (!interfaceType.IsInterface) { throw new InvalidOperationException( "MakeTypeImplementing<T> requires an interface for the type parameter"); } var identifier = Guid.NewGuid().ToString("N"); var moduleName = string.Join("_", identifier, "_Gen_", interfaceType.Name); var modBuilder = DynamicAssemblyBuilder.DefineDynamicModule(moduleName); var generatedTypeName = interfaceType.Name + "_Duck_" + identifier; var typeBuilder = modBuilder.DefineType(generatedTypeName, TypeAttributes.Public); var attribConstructor = typeof(IsADuckAttribute).GetConstructor(new Type[0]); // we have full control over the constructor; testing for null is a waste of time. // ReSharper disable once AssignNullToNotNullAttribute var attribBuilder = new CustomAttributeBuilder(attribConstructor, new object[0]); typeBuilder.SetCustomAttribute(attribBuilder); CopyCustomAttributes(interfaceType, typeBuilder); typeBuilder.AddInterfaceImplementation(interfaceType); var shimField = AddShimField(typeBuilder); var allInterfaceTypes = interfaceType.GetAllImplementedInterfaces(); AddAllPropertiesAsShimmable(typeBuilder, allInterfaceTypes, shimField); AddAllMethodsAsShimmable(typeBuilder, allInterfaceTypes, shimField); AddDefaultConstructor(typeBuilder, shimField, interfaceType, isFuzzy); AddObjectWrappingConstructors(typeBuilder, shimField, interfaceType, isFuzzy); AddDictionaryWrappingConstructors(typeBuilder, shimField, interfaceType); #if NETSTANDARD return(typeBuilder.CreateTypeInfo()); #else return(typeBuilder.CreateType()); #endif }
private static Type InternalCreateType(IDataReader reader, IEnumerable <Type> implInterfaceTypes) { var guid = Guid.NewGuid().ToString("N"); var typeBuilder = new DynamicAssemblyBuilder("_Dynamic_" + guid).DefineType("$<>" + guid); foreach (var type in implInterfaceTypes) { typeBuilder.ImplementInterface(type); } var length = reader.FieldCount; var fields = new DynamicFieldBuilder[length]; for (var i = 0; i < length; i++) { var name = GetFieldName(reader.GetName(i)); var type = reader.GetFieldType(i); var fieldBuilder = typeBuilder.DefineField("<>__" + name, type); typeBuilder.DefineProperty(name, type).DefineGetSetMethods(fieldBuilder); fields[i] = fieldBuilder; } var constructorBuilder = typeBuilder.DefineConstructor(new[] { typeof(IDataReader), typeof(IRecordWrapper) }, ilCoding: bc => bc.Emitter .For(0, length, (e, i) => e.ldarg_0 .ldarg_2 .ldarg_1 .ldc_i4(i) .callvirt(RecordWrapHelper.GetGetValueMethod(reader.GetFieldType(i))) .stfld(fields[i].FieldBuilder)) .ret()); constructorBuilder.DefineParameter("reader"); constructorBuilder.DefineParameter("wrapper"); return(typeBuilder.CreateType()); }
/// <summary> /// 使用指定的属性集合创建新的对象类型。 /// </summary> /// <param name="newTypeName"></param> /// <param name="properties"></param> /// <returns></returns> private static Type BuildNewObjectType(string newTypeName, IEnumerable <PropertyInfo> properties) { var assembly = new DynamicAssemblyBuilder("__DynamicAssembly_ExtendTypes"); var typeBuilder = assembly.DefineType(newTypeName); //构造方法的参数类型集合 var constructorParTypes = new List <Type>(); //属性set方法的集合 var setMethodBuilders = new List <DynamicMethodBuilder>(); foreach (var pro in properties) { if (pro.CanRead) { var pbuilder = typeBuilder.DefineProperty(pro.Name, pro.PropertyType); //定义get和set方法 pbuilder.DefineGetMethod(); setMethodBuilders.Add(pbuilder.DefineSetMethod(pro.CanWrite ? VisualDecoration.Public : VisualDecoration.Internal)); constructorParTypes.Add(pro.PropertyType); } } //定义一个构造方法,使用两个类型中的所有属性作为方法的参数 if (constructorParTypes.Count > 0) { typeBuilder.DefineConstructor(constructorParTypes.ToArray()).AppendCode(e => { //在构造方法中,对每一个属性进行赋值 e.Each(setMethodBuilders, (e1, b, i) => e1.ldarg_0.ldarg(i + 1).call(b.MethodBuilder) ).ret(); }); } return(typeBuilder.CreateType()); }
public void DefineTypeTest() { var assemblyBuilder = new DynamicAssemblyBuilder("dynamicAssembly1"); assemblyBuilder.DefineType("class1"); }
private DynamicTypeBuilder CreateBuilder() { var assemblyBuilder = new DynamicAssemblyBuilder("assemblyTests"); return(assemblyBuilder.DefineType("testClass")); }
static TinyMapper() { _targetMapperBuilder = new TargetMapperBuilder(DynamicAssemblyBuilder.Get()); _config = new TinyMapperConfig(_targetMapperBuilder); }
public void Inject(Type entityType, DynamicAssemblyBuilder assemblyBuilder, DynamicTypeBuilder typeBuilder) { var propertyBuilder = typeBuilder.DefineProperty("_id", typeof(ObjectId)); propertyBuilder.DefineGetSetMethods(); }
/// <summary> /// 初始化 <see cref="RelationshipBuilder"/> 类的新实例。 /// </summary> /// <param name="assemblyBuilder">一个 <see cref="DynamicAssemblyBuilder"/> 容器。</param> public RelationshipBuilder(DynamicAssemblyBuilder assemblyBuilder = null) { m_assemblyBuilder = assemblyBuilder ?? new DynamicAssemblyBuilder("<DynamicRelationship>_" + Guid.NewGuid().ToString("N")); }
private static ModuleBuilder CreateModuleBuilder() { var moduleName = "__PeanutButter_DuckTyped_Gen__"; return(DynamicAssemblyBuilder.DefineDynamicModule(moduleName)); }
public void DefineEnumTest() { var assemblyBuilder = new DynamicAssemblyBuilder("dynamicAssembly1"); assemblyBuilder.DefineEnum("enum1"); }
public void DefineInterfaceTest() { var assemblyBuilder = new DynamicAssemblyBuilder("dynamicAssembly1"); assemblyBuilder.DefineInterface("interface1"); }