问题
Using the Roslyn June 2012 CTP:
Is there a way to provide the Roslyn C# Interactive/REPL with a .config file for the code being explored? A simple example scenario is code which depends on a connection string which it would usually obtain from the app.config/web.config.
回答1:
This is actually possible now (and may have been at the time this question was asked). Simply create a LoadConfig.csx file with the following:
#r "System.Configuration"
using System;
using System.IO;
using System.Linq;
var paths = new[] { Path.Combine(Environment.CurrentDirectory, "Web.config"), Path.Combine(Environment.CurrentDirectory, "App.config") };
var configPath = paths.FirstOrDefault(p => File.Exists(p));
if (configPath != null)
{
// Set new configuration path
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", configPath);
// Reset current configuration load state
var t = typeof(System.Configuration.ConfigurationManager);
var f = t.GetField("s_initState", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
f.SetValue(null, 0);
}
Save the file somewhere you'll remember and return to the project you want to load in visual studio. Right click the project and select "Reset C# Interactive from Project". Once the C# interactive window is finished loading call:
#load "C:\path\to\LoadConfig.csx"
NOTE: You must call this immediately after loading the project. If any configuration lookups occur before you load this script then this script will fail to work.
Now the C# Interactive window should have access to your project settings.
回答2:
There isn't a way to do this right now, though it is something that we're thinking about for the future.
In the meantime, could you factor your code to take the connection string as a parameter, and just pass it into the method in the Interactive Window?
回答3:
Already accepted answer didn't work for me; based on the comments to the accepted answer, it didn't work for 2 others as well. Below solution worked for me.
Update the config file of c# interactive (REPL) which is located at
AppDomain.CurrentDomain.SetupInformation.ConfigurationFileRe-initialize REPL.
来源:https://stackoverflow.com/questions/10906946/access-to-config-files-in-roslyn-repl