To access an object across AppDomain
boundary, the class must be derived from MarshalByRefObject
.
From MSDN Page:
Types must inherit from MarshalByRefObject when the type is used across application domain boundaries, and the state of the object must not be copied because the members of the object are not usable outside the application domain where they were created.
That means, your Sample Class should derive from MarshalByRefObject
:
[Serializable]
public class Sample : MarshalByRefObject
{
public void DebugPrint()
{
Console.WriteLine("=====================================");
Console.WriteLine(ConfigurationManager.AppSettings.Count);
Console.WriteLine("Reading config: =====|{0}|=====", ConfigurationManager.AppSettings["MyData"]);
Console.WriteLine("=====================================");
}
}
I have tried in a sample app, but with a Config XML instead of calling SetConfigurationData
and it works, Below is my Sample code for your reference:
var setup = new AppDomainSetup();
setup.ConfigurationFile = "SandBoxConfig.xml";
var sandbox = AppDomain.CreateDomain("Sandbox", null, setup);
var verifier = (Sample)sandbox.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Sample).FullName);
verifier.DebugPrint();
EDIT
From MSDN Page, AppDomainSetup.SetConfigurationBytes Method
Some consumers of configuration file information do not use the information stored by the SetConfigurationBytes method. The runtime does not enforce this. To ensure that all configuration file information is replaced in a new application domain, use the ConfigurationFile property to specify a configuration file. The SetConfigurationBytes method does affect assembly binding.
So, I suspect, types in System.Configuration
namespace (like ConfigurationManager
) ignoring the configuration data provided via SetConfigurationBytes
.