|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Linq; |
| 4 | +using System.Reflection; |
1 | 5 | using System.Threading.Tasks; |
| 6 | +using Microsoft.CodeAnalysis; |
| 7 | +using Microsoft.CodeAnalysis.CSharp; |
| 8 | +using Microsoft.CodeAnalysis.Emit; |
2 | 9 | using Microsoft.VisualStudio.TestTools.UnitTesting; |
3 | 10 | using RazorEngineCore.Tests.Models; |
4 | 11 |
|
@@ -454,5 +461,61 @@ public async Task TestCompileAndRun_LinqAsync() |
454 | 461 |
|
455 | 462 | Assert.AreEqual(expected, actual); |
456 | 463 | } |
| 464 | + |
| 465 | + [TestMethod] |
| 466 | + public async Task TestCompileAndRun_MetadataReference() |
| 467 | + { |
| 468 | + string greetingClass = @" |
| 469 | +namespace TestAssembly |
| 470 | +{ |
| 471 | + public static class Greeting |
| 472 | + { |
| 473 | + public static string GetGreeting(string name) |
| 474 | + { |
| 475 | + return ""Hello, "" + name + ""!""; |
| 476 | + } |
| 477 | + } |
| 478 | +} |
| 479 | +"; |
| 480 | + |
| 481 | + RazorEngine razorEngine = new RazorEngine(); |
| 482 | + IRazorEngineCompiledTemplate template = await razorEngine.CompileAsync(@" |
| 483 | +@using TestAssembly |
| 484 | +<p>@Greeting.GetGreeting(""Name"")</p> |
| 485 | +", builder => |
| 486 | + { |
| 487 | + // This needs to be done in the builder to have access to all of the assemblies added through |
| 488 | + // the various AddAssemblyReference options |
| 489 | + CSharpCompilation compilation = CSharpCompilation.Create( |
| 490 | + "TestAssembly", |
| 491 | + new [] |
| 492 | + { |
| 493 | + CSharpSyntaxTree.ParseText(greetingClass) |
| 494 | + }, |
| 495 | + builder.Options.ReferencedAssemblies |
| 496 | + .Select(ass => MetadataReference.CreateFromFile(ass.Location)).ToList(), |
| 497 | + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) |
| 498 | + ); |
| 499 | + MemoryStream memoryStream = new MemoryStream(); |
| 500 | + EmitResult emitResult = compilation.Emit(memoryStream); |
| 501 | + if (!emitResult.Success) return; |
| 502 | + |
| 503 | + memoryStream.Position = 0; |
| 504 | + builder.AddMetadataReference(MetadataReference.CreateFromStream(memoryStream)); |
| 505 | + |
| 506 | + // Add an assembly resolver so the assembly can be found |
| 507 | + AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) => |
| 508 | + new AssemblyName(eventArgs.Name ?? string.Empty).Name == "TestAssembly" |
| 509 | + ? Assembly.Load(memoryStream.ToArray()) |
| 510 | + : null; |
| 511 | + }); |
| 512 | + |
| 513 | + string expected = @" |
| 514 | +<p>Hello, Name!</p> |
| 515 | +"; |
| 516 | + string actual = await template.RunAsync(); |
| 517 | + |
| 518 | + Assert.AreEqual(expected, actual); |
| 519 | + } |
457 | 520 | } |
458 | 521 | } |
0 commit comments