If I create two application domains and load the same assembly of same version. Would they be treated/isolated differently ?
I have created a new assembly named it as DyTest
:-
using System;
namespace DyTest
{
[Serializable]
public sealed class Program
{
private static int _call = 0;
public static int call()
{
_call += 1;
return _call;
}
}
}
Build it and referenced it to console app. and call it as below:-
static void Main(string[] args)
{
CreateDomainAndDisplayValue("test1");
CreateDomainAndDisplayValue("test2");
Console.ReadLine();
}
static void CreateDomainAndDisplayValue(string domainName)
{
AppDomainSetup domaininfo = new AppDomainSetup();
domaininfo.ApplicationBase = "D:\\Test\\CN_TEST\\CN_TEST\\bin\\Debug\\";
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AppDomain domain = AppDomain.CreateDomain(domainName, adevidence, domaininfo);
var t = (domain.CreateInstanceAndUnwrap("DyTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "DyTest.Program")).GetType();
MethodInfo m = t.GetMethod("call");
object obj = Activator.CreateInstance(t);
Console.WriteLine((int)m.Invoke(obj, new object[] { }));
}
Now test1
is returning 1
Now test2
is returning 2
As variable _call
is static variable, so it means either my understanding is not correct about Application Domains or I am missing something above.
I am expecting
test1
should return 1
test2
should return 1
Can I achieve this by AppDomain?
Update 1 As referred here, I have changed the code as below:-
using System;
namespace DyTest
{
public sealed class Program : MarshalByRefObject
{
private static int _call = 0;
public static int call()
{
_call += 1;
return _call;
}
}
}
Result:-
Now test1
is returning 1 and test2` is returning 2
No difference.
Update 2 : got the solution from Eric's answer on this topic here
Modified method as follows :-
static void CreateDomainAndDisplayValue(string domainName)
{
AppDomainSetup domaininfo = new AppDomainSetup();
domaininfo.ApplicationBase = "D:\\Test\\CN_TEST\\CN_TEST\\bin\\Debug\\";
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AppDomain domain = AppDomain.CreateDomain(domainName, adevidence, domaininfo);
DyTest.Program objInstance = domain.CreateInstanceAndUnwrap("DyTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "DyTest.Program") as DyTest.Program;
Console.WriteLine(objInstance.callFromEric());
}
And
using System;
namespace DyTest
{
public sealed class Program : MarshalByRefObject
{
private static int _call = 0;
public static int call()
{
_call += 1;
return _call;
}
public int callFromEric()
{
return Program.call();
}
}
}
Output is 1 1