- 增加DynamicEntity立nuget包

This commit is contained in:
d4ilys 2023-05-05 10:53:28 +08:00
parent 64c9d0bdee
commit b17c2ef4a5
4 changed files with 401 additions and 0 deletions

View File

@ -0,0 +1,231 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Security.Cryptography;
using System.Text;
namespace FreeSql
{
/// <summary>
/// 动态创建实体类型
/// </summary>
public class DynamicCompileBuilder
{
private string _className = string.Empty;
private Attribute[] _tableAttributes = null;
private List<DynamicPropertyInfo> _properties = new List<DynamicPropertyInfo>();
private Type _superClass = null;
/// <summary>
/// 配置Class
/// </summary>
/// <param name="className">类名</param>
/// <param name="attributes">类标记的特性[Table(Name = "xxx")] [Index(xxxx)]</param>
/// <returns></returns>
public DynamicCompileBuilder Class(string className, params Attribute[] attributes)
{
_className = className;
_tableAttributes = attributes;
return this;
}
/// <summary>
/// 配置属性
/// </summary>
/// <param name="propertyName">属性名称</param>
/// <param name="propertyType">属性类型</param>
/// <param name="attributes">属性标记的特性-支持多个</param>
/// <returns></returns>
public DynamicCompileBuilder Property(string propertyName, Type propertyType, params Attribute[] attributes)
{
_properties.Add(new DynamicPropertyInfo()
{
PropertyName = propertyName,
PropertyType = propertyType,
Attributes = attributes
});
return this;
}
/// <summary>
/// 配置父类
/// </summary>
/// <param name="superClass">父类类型</param>
/// <returns></returns>
public DynamicCompileBuilder SuperClass(Type superClass)
{
_superClass = superClass;
return this;
}
private void SetTableAttribute(ref TypeBuilder typeBuilder)
{
if (_tableAttributes == null) return;
foreach (var tableAttribute in _tableAttributes)
{
var propertyValues = new ArrayList();
if (tableAttribute == null) continue;
var classCtorInfo = tableAttribute.GetType().GetConstructor(new Type[] { });
var propertyInfos = tableAttribute.GetType().GetProperties().Where(p => p.CanWrite == true).ToArray();
foreach (var propertyInfo in propertyInfos)
propertyValues.Add(propertyInfo.GetValue(tableAttribute));
//可能存在有参构造
if (classCtorInfo == null)
{
var constructorTypes = propertyInfos.Select(p => p.PropertyType);
classCtorInfo = tableAttribute.GetType().GetConstructor(constructorTypes.ToArray());
var customAttributeBuilder = new CustomAttributeBuilder(classCtorInfo, propertyValues.ToArray());
typeBuilder.SetCustomAttribute(customAttributeBuilder);
}
else
{
var customAttributeBuilder = new CustomAttributeBuilder(classCtorInfo, new object[0], propertyInfos,
propertyValues.ToArray());
typeBuilder.SetCustomAttribute(customAttributeBuilder);
}
}
}
private void SetPropertys(ref TypeBuilder typeBuilder)
{
foreach (var pinfo in _properties)
{
if (pinfo == null)
continue;
var propertyName = pinfo.PropertyName;
var propertyType = pinfo.PropertyType;
//设置字段
var field = typeBuilder.DefineField($"_{FirstCharToLower(propertyName)}", propertyType,
FieldAttributes.Private);
var firstCharToUpper = FirstCharToUpper(propertyName);
//设置属性方法
var methodGet = typeBuilder.DefineMethod($"Get{firstCharToUpper}", MethodAttributes.Public,
propertyType, null);
var methodSet = typeBuilder.DefineMethod($"Set{firstCharToUpper}", MethodAttributes.Public, null,
new Type[] { propertyType });
var ilOfGet = methodGet.GetILGenerator();
ilOfGet.Emit(OpCodes.Ldarg_0);
ilOfGet.Emit(OpCodes.Ldfld, field);
ilOfGet.Emit(OpCodes.Ret);
var ilOfSet = methodSet.GetILGenerator();
ilOfSet.Emit(OpCodes.Ldarg_0);
ilOfSet.Emit(OpCodes.Ldarg_1);
ilOfSet.Emit(OpCodes.Stfld, field);
ilOfSet.Emit(OpCodes.Ret);
//设置属性
var propertyBuilder =
typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, propertyType, null);
propertyBuilder.SetGetMethod(methodGet);
propertyBuilder.SetSetMethod(methodSet);
foreach (var pinfoAttribute in pinfo.Attributes)
{
//设置特性
SetPropertyAttribute(ref propertyBuilder, pinfoAttribute);
}
}
}
private void SetPropertyAttribute<T>(ref PropertyBuilder propertyBuilder, T tAttribute)
{
if (tAttribute == null) return;
var propertyInfos = tAttribute.GetType().GetProperties().Where(p => p.CanWrite == true).ToArray();
var constructor = tAttribute.GetType().GetConstructor(new Type[] { });
var propertyValues = new ArrayList();
foreach (var propertyInfo in propertyInfos)
propertyValues.Add(propertyInfo.GetValue(tAttribute));
var customAttributeBuilder =
new CustomAttributeBuilder(constructor, new object[0], propertyInfos, propertyValues.ToArray());
propertyBuilder.SetCustomAttribute(customAttributeBuilder);
}
/// <summary>
/// Emit动态创建出Class - Type
/// </summary>
/// <returns></returns>
public Type Build()
{
//初始化AssemblyName的一个实例
var assemblyName = new AssemblyName("FreeSql.DynamicCompileBuilder");
//设置程序集的名称
var defineDynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
//动态在程序集内创建一个模块
var defineDynamicModule =
defineDynamicAssembly.DefineDynamicModule("FreeSql.DynamicCompileBuilder.Dynamics");
//动态的在模块内创建一个类
var typeBuilder =
defineDynamicModule.DefineType(_className, TypeAttributes.Public | TypeAttributes.Class, _superClass);
//设置TableAttribute
SetTableAttribute(ref typeBuilder);
//设置属性
SetPropertys(ref typeBuilder);
//创建类的Type对象
return typeBuilder.CreateType();
}
/// <summary>
/// 首字母小写
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private string FirstCharToLower(string input)
{
if (string.IsNullOrEmpty(input))
return input;
string str = input.First().ToString().ToLower() + input.Substring(1);
return str;
}
/// <summary>
/// 首字母大写
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private string FirstCharToUpper(string input)
{
if (string.IsNullOrEmpty(input))
return input;
string str = input.First().ToString().ToUpper() + input.Substring(1);
return str;
}
private static string Md5Encryption(string inputStr)
{
var result = string.Empty;
//32位大写
using (var md5 = MD5.Create())
{
var resultBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(inputStr));
result = BitConverter.ToString(resultBytes);
}
return result;
}
class DynamicPropertyInfo
{
public string PropertyName { get; set; } = string.Empty;
public Type PropertyType { get; set; }
public Attribute[] Attributes { get; set; }
}
}
}

View File

@ -0,0 +1,74 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace FreeSql.Extensions.DynamicEntity
{
/// <summary>
/// 动态创建对象帮助类
/// </summary>
public class DynamicCompileHelper
{
/// <summary>
/// 动态构建Class - Type
/// </summary>
/// <returns></returns>
public static DynamicCompileBuilder DynamicBuilder()
{
return new DynamicCompileBuilder();
}
/// <summary>
/// 委托缓存
/// </summary>
private static readonly ConcurrentDictionary<string, Delegate>
DelegateCache = new ConcurrentDictionary<string, Delegate>();
/// <summary>
/// 设置动态对象的属性值
/// </summary>
/// <param name="type"></param>
/// <param name="porpertys"></param>
/// <returns></returns>
public static object CreateObjectByType(Type type, Dictionary<string, object> porpertys)
{
if (type == null)
return null;
object istance = Activator.CreateInstance(type);
if (istance == null)
return null;
//根据key确定缓存
var cacheKey = $"{type.GetHashCode()}{porpertys.GetHashCode()}";
var dynamicDelegate = DelegateCache.GetOrAdd(cacheKey, key =>
{
//表达式目录树构建委托
var typeParam = Expression.Parameter(type);
var dicParamType = typeof(Dictionary<string, object>);
var dicParam = Expression.Parameter(dicParamType);
var exps = new List<Expression>();
var tempRef = Expression.Variable(typeof(object));
foreach (var pinfo in porpertys)
{
var propertyInfo = type.GetProperty(pinfo.Key);
if (propertyInfo == null)
continue;
var propertyName = Expression.Constant(pinfo.Key, typeof(string));
exps.Add(Expression.Call(dicParam, dicParamType.GetMethod("TryGetValue"), propertyName, tempRef));
exps.Add(Expression.Assign(Expression.MakeMemberAccess(typeParam, propertyInfo),
Expression.Convert(tempRef, propertyInfo.PropertyType)));
exps.Add(Expression.Assign(tempRef, Expression.Default(typeof(object))));
}
var returnTarget = Expression.Label(type);
exps.Add(Expression.Return(returnTarget, typeParam));
exps.Add(Expression.Label(returnTarget, Expression.Default(type)));
var block = Expression.Block(new[] { tempRef }, exps);
var @delegate = Expression.Lambda(block, typeParam, dicParam).Compile();
return @delegate;
});
var dynamicInvoke = dynamicDelegate.DynamicInvoke(istance, porpertys);
return dynamicInvoke;
}
}
}

View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.1;net451;net45;</TargetFrameworks>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<DocumentationFile>FreeSql.Extensions.DynamicEntity.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<None Update="FreeSql.Extensions.DynamicEntity.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,81 @@
<?xml version="1.0"?>
<doc>
<assembly>
<name>FreeSql.Extensions.DynamicEntity</name>
</assembly>
<members>
<member name="T:FreeSql.DynamicCompileBuilder">
<summary>
动态创建实体类型
</summary>
</member>
<member name="M:FreeSql.DynamicCompileBuilder.Class(System.String,System.Attribute[])">
<summary>
配置Class
</summary>
<param name="className">类名</param>
<param name="attributes">类标记的特性[Table(Name = "xxx")] [Index(xxxx)]</param>
<returns></returns>
</member>
<member name="M:FreeSql.DynamicCompileBuilder.Property(System.String,System.Type,System.Attribute[])">
<summary>
配置属性
</summary>
<param name="propertyName">属性名称</param>
<param name="propertyType">属性类型</param>
<param name="attributes">属性标记的特性-支持多个</param>
<returns></returns>
</member>
<member name="M:FreeSql.DynamicCompileBuilder.SuperClass(System.Type)">
<summary>
配置父类
</summary>
<param name="superClass">父类类型</param>
<returns></returns>
</member>
<member name="M:FreeSql.DynamicCompileBuilder.Build">
<summary>
Emit动态创建出Class - Type
</summary>
<returns></returns>
</member>
<member name="M:FreeSql.DynamicCompileBuilder.FirstCharToLower(System.String)">
<summary>
首字母小写
</summary>
<param name="input"></param>
<returns></returns>
</member>
<member name="M:FreeSql.DynamicCompileBuilder.FirstCharToUpper(System.String)">
<summary>
首字母大写
</summary>
<param name="input"></param>
<returns></returns>
</member>
<member name="T:FreeSql.Extensions.DynamicEntity.DynamicCompileHelper">
<summary>
动态创建对象帮助类
</summary>
</member>
<member name="M:FreeSql.Extensions.DynamicEntity.DynamicCompileHelper.DynamicBuilder">
<summary>
动态构建Class - Type
</summary>
<returns></returns>
</member>
<member name="F:FreeSql.Extensions.DynamicEntity.DynamicCompileHelper.DelegateCache">
<summary>
委托缓存
</summary>
</member>
<member name="M:FreeSql.Extensions.DynamicEntity.DynamicCompileHelper.CreateObjectByType(System.Type,System.Collections.Generic.Dictionary{System.String,System.Object})">
<summary>
设置动态对象的属性值
</summary>
<param name="type"></param>
<param name="porpertys"></param>
<returns></returns>
</member>
</members>
</doc>