public void Test() { var myHostObject = new MyHostObject { Value1 = "Testing Value 1", Value2 = "This is Value 2" }; var engine = new ScriptEngine(); var session = engine.CreateSession(myHostObject); session.AddReference(myHostObject.GetType().Assembly.Location); session.AddReference("System"); session.AddReference("System.Core"); session.ImportNamespace("System"); // "Execute" our method so we can call it. session.Execute("public string UpdateHostObject() { Value1 = \"V1\"; Value2 = \"V2\"; return Value1 + Value2;}"); var s = session.Execute <string>("UpdateHostObject()"); //s will return "V1V2" and your instance of myHostObject was also changed. }
public void SetGetHostObjectInProject() { string projectContents = @" <Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <Target Name=`Build` > <MakeDir Directories=`c:\rajeev` /> <Csc Sources=`foo.cs` /> </Target> </Project> "; Project project = ObjectModelHelpers.CreateInMemoryProject(projectContents); MyHostObject hostObject1 = new MyHostObject(); MyHostObject hostObject2 = new MyHostObject(); // Set hostObject1 to the "MakeDir" task, and set hostObject2 to the "Csc" task. foreach (Target target in project.Targets) { foreach (BuildTask myTask in target) { if (myTask.Name == "MakeDir") { myTask.HostObject = hostObject1; } else if (myTask.Name == "Csc") { myTask.HostObject = hostObject2; } else { Assertion.Assert("Unknown task", false); } } } bool foundMakeDir = false; bool foundCsc = false; // Now retrieve the host objects for "MakeDir" and "Csc", and confirm they're the // same ones we set originally. foreach (Target target in project.Targets) { foreach (BuildTask myTask in target) { if (myTask.Name == "MakeDir") { Assertion.AssertSame(myTask.HostObject, hostObject1); Assertion.Assert(myTask.HostObject != hostObject2); foundMakeDir = true; } else if (myTask.Name == "Csc") { Assertion.AssertSame(myTask.HostObject, hostObject2); Assertion.Assert(myTask.HostObject != hostObject1); foundCsc = true; } else { Assertion.Assert("Unknown task", false); } } } Assertion.Assert(foundMakeDir && foundCsc); }