- A+
所属分类:.NET技术
首先依赖注入 懒得下载autofac了 直接用程序集进行批量注入
private static WebApplicationBuilder builder; internal static void Load(WebApplicationBuilder web) { builder = web; builder.Services.Configure<ApiBehaviorOptions>(options => options.SuppressModelStateInvalidFilter = true); Assembly.Load("TestApplication").ExportedTypes.LoadImp(); builder.Services.AddSingleton(typeof(ITestGren<>), typeof(TestGren<>)); } private static void LoadImp(this IEnumerable<Type> type) { type= type.Where(d => d.IsClass&&!d.IsAbstract); foreach (var item in type) { ///检查是不是泛型类 if (item.GetGenericArguments().Length is 0) item.GetInterfaces().LoadInter(item); } } private static void LoadInter(this Type[] type,Type ImpType) { foreach (var item in type) { if (item.GetGenericArguments().Length is 0) builder.Services.AddSingleton(item,ImpType); } }
可惜泛型类不能直接注入 需要自己写,反正自己也不怎么写泛型类
然后我们的接口要验签就创建一个类来继承ValidationAttribute特性
[CheckSgValidation(ErrorMessage ="签名错误")] public class TestModel { public string Sg { get; set; } } public class CsModel:TestModel { public int MyProperty { get; set; } } [AttributeUsage(AttributeTargets.Class )] public class CheckSgValidation: ValidationAttribute { private string SgName = "Sg"; public CheckSgValidation(string sgName) { this.SgName = sgName; } public CheckSgValidation() { } public override bool IsValid(object? value) { StringBuilder sb = new StringBuilder(); foreach (var item in value.GetType().GetProperties()) { if (item.Name == SgName) continue; sb.Append(item.GetValue(value)); } return sb.ToString() == value.GetType().GetProperty(SgName).GetValue(value).ToString(); } }
我是用单独一个类来写上我们自定义的特性, 尝试过用表达式树进行验证的 可惜参数为object就不行 不知道怎么处理这个问题
这样用反射确实可以用