/// <summary> /// 引用第三方包,配置文件中配置引用key=对应服务的应用名 /// </summary> /// <param name="metadataReferences"></param> /// <param name="appName"></param> private static void ReferenceAssemblyByAppName(AdvancedCache <string, List <MetadataReference> > metadataReferences, string appName) { //这里配置的程序集引用要写文件全名,包括路径和后缀 var assemblyInfos = AssemblyReferenceConfig.GetAssemblyInfoByAppName(appName); //为不为空都把默认执行路径加上扫描 var dirs = SettingsConfigHelper.GetReferenceDirs(); if (dirs == null || !dirs.Any()) { dirs = new List <string>(); } dirs.Insert(0, AppContext.BaseDirectory); if (assemblyInfos != null && assemblyInfos.Any()) { foreach (var assemblyInfo in assemblyInfos) { foreach (var dir in dirs) { var fileFullPath = Path.Combine(dir, assemblyInfo.Assembly); if (!File.Exists(fileFullPath)) { _logger.Debug($"reference file [{fileFullPath}] in config not found."); continue; } //如果文件存在,则加载完成后跳过后续扫描 metadataReferences[AppSettingsConfigHelper.GetAppName()].Add(MetadataReference.CreateFromFile(fileFullPath)); break; } } } }
/// <summary> /// Create Assembly whick will run /// </summary> /// <param name="script"></param> /// <param name="errorMsg"></param> /// <returns></returns> private Assembly CreateAsmExecutor(string script, out string errorMsg) { errorMsg = null; var assemblyName = _scriptHash; var sourceTree = CSharpSyntaxTree.ParseText(script, path: assemblyName + ".cs", encoding: Encoding.UTF8); var references = _metadataReferences[AppSettingsConfigHelper.GetAppName()]; var compilation = CSharpCompilation.Create(assemblyName, new[] { sourceTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithOptimizationLevel(SettingsConfigHelper.IsDebug() ? OptimizationLevel.Debug : OptimizationLevel.Release)); Assembly assembly; using (var assemblyStream = new MemoryStream()) { using (var pdbStream = new MemoryStream()) { var emitResult = compilation.Emit(assemblyStream, pdbStream); if (emitResult.Success) { var assemblyBytes = assemblyStream.GetBuffer(); var pdbBytes = pdbStream.GetBuffer(); assembly = Assembly.Load(assemblyBytes, pdbBytes); //output files if (SettingsConfigHelper.IsOutPutFiles()) { if (SettingsConfigHelper.IsOutPutAllFiles()) { OutputDynamicScriptAllFile(script, assemblyName, assemblyBytes, pdbBytes); } else { OutputDynamicScriptDllFile(assemblyName, assemblyBytes); } } } else { var msgs = new StringBuilder(); foreach (var msg in emitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).Select(d => string.Format("[{0}]:{1}({2})", d.Id, d.GetMessage(), d.Location.GetLineSpan().StartLinePosition))) { msgs.AppendLine(msg); if (SettingsConfigHelper.IsOutPutFiles()) { WriteDynamicScriptCs(Path.Combine(EnsureOutputPath(), assemblyName + ".cs"), script); } _logger.Error(String.Format("{0}:{1}:{2}:{3}:{4}", _tenantId, "CSharp", _projectName, msg, _scriptHash)); } errorMsg = msgs.ToString(); return(null); } } } _logger.Debug($"CreateAsmExecutor->_context:{_tenantId},{"CSharp"}, {_projectName},{_scriptHash} _scriptTypeDict:{_scriptTypeDict?.Count} _metadataReferences:{ _metadataReferences[_projectName]?.Count}"); return(assembly); }
public static void InitMetadataReferences(AdvancedCache <string, List <MetadataReference> > metadataReferences) { if (!metadataReferences.ContainsKey(AppSettingsConfigHelper.GetAppName())) { metadataReferences.Insert(AppSettingsConfigHelper.GetAppName(), new List <MetadataReference>(), CacheStrategy.Permanent); } ReferenceNecessaryAssembly(metadataReferences); ReferenceSystemAssembly(metadataReferences); ReferenceExternalAssembly(metadataReferences); var referenceArrayJson = Newtonsoft.Json.JsonConvert.SerializeObject(metadataReferences[AppSettingsConfigHelper.GetAppName()]?.Select(t => t.Display)?.ToArray()); _logger.Debug($"dll加载完毕,加载信息如下:{referenceArrayJson}"); }
private static void ReferenceNecessaryAssembly(AdvancedCache <string, List <MetadataReference> > metadataReferences) { var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); var references = new[] { MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "netstandard.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "Microsoft.CSharp.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Collections.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Linq.dll")), MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(System.Xml.XmlReader).Assembly.Location), MetadataReference.CreateFromFile(typeof(System.Net.HttpWebRequest).Assembly.Location), MetadataReference.CreateFromFile(typeof(System.Net.Http.HttpClient).Assembly.Location), MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location), MetadataReference.CreateFromFile(typeof(System.Runtime.Serialization.DataContractSerializer).Assembly.Location), }; metadataReferences[AppSettingsConfigHelper.GetAppName()].AddRange(references); }
public static List <AssemblyInfo> GetCurrentAppAssemblyReferenceInfos() { return(Instance?.Where(t => t.AppName.ToUpper().Equals(DefaultAppName) || t.AppName.Equals(AppSettingsConfigHelper.GetAppName()))?.Select(t => new AssemblyInfo { AppName = t.AppName, Assembly = t.Assembly })?.ToList()); }
public void GetCurrentAppName() { var currentAppName = AppSettingsConfigHelper.GetAppName(); Assert.NotNull(currentAppName); }
private static void ReferenceExternalAssembly(AdvancedCache <string, List <MetadataReference> > metadataReferences) { ReferenceAssemblyByAppName(metadataReferences, AppSettingsConfigHelper.GetAppName()); }