/// <summary> /// Generates the class en compiles it into a producer. /// </summary> /// <param name="code">The code.</param> /// <returns>The producer.</returns> public IProducer CreateProducer(string code) { var args = new CompilerInstructions(); args.ClassName = "_" + Guid.NewGuid().ToString("N"); args.Code = @"<<USINGS>> public class <<CLASS_NAME>>: <<BASE_TYPE>> { public <<MODIFIER>> object Run() { <<CODE>>; return null; } }" ; args.Code = args.Code.Replace("<<CLASS_NAME>>", args.ClassName); args.Code = args.Code.Replace("<<BASE_TYPE>>", FixFullName(_producerType)); args.Code = args.Code.Replace("<<CODE>>", code); args.AssemblyLocations.AddRange(this.AssemblyLocations); if (Usings.Count > 0) { string usings = "using " + String.Join(";\nusing ", Usings) + ";"; args.Code = args.Code.Replace("<<USINGS>>", usings); } else { args.Code = args.Code.Replace("<<USINGS>>", ""); } if (_producerType.IsClass) { args.Code = args.Code.Replace("<<MODIFIER>>", "override"); } else { args.Code = args.Code.Replace("<<MODIFIER>>", ""); } return(_compiler.CompileAndCreateObject <IProducer>(args)); }
public void RoslynCompilation_HelloWorld_Assembly() { var compiler = new RoslynCompiler(); var instruction = new CompilerInstructions(); instruction.AssemblyLocations.Add(typeof(IProducer).Assembly.Location); instruction.AssemblyLocations.Add(typeof(object).Assembly.Location); instruction.ClassName = "_" + Guid.NewGuid().ToString("N"); instruction.Code = @"using System; public class " + instruction.ClassName + ": " + typeof(IProducer).FullName + @" { public object Run() { return ""Hello world!""; } }"; string result = compiler.RunProducer(instruction) as string; Assert.AreEqual("Hello world!", result); }