Say I have the following class hierarchy defined in a class library:
public interface IFoo
{
string GetMsg();
}
public abstract class FooBase
{
public virtual string GetMsg()
{
return "Foobase msg";
}
}
public class Foo : FooBase, IFoo
{
#region IFoo Members
public new string GetMsg()
{
return base.GetMsg();
}
#endregion
}
I'm consuming this assembly in a console application and using reflection I'm creating an instance of the Foo class typed to IFoo as follows:
Assembly a = Assembly.LoadFile(Path.GetFullPath("TestClassLib.dll"));
var typeDef = a.GetType("TestClassLib.Foo");
var fooInst = Activator.CreateInstance(typeDef) as IFoo;
string msg = fooInst.GetMsg();
The above works fine. Now if I take this code and port it to an ASP.NET Web web page like so:
namespace TestWebApp
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string filePath = Server.MapPath(@"~/bin/TestClassLib.dll");
Assembly a = Assembly.LoadFile(Path.GetFullPath(filePath));
var typeDef = a.GetType("TestClassLib.Foo");
var fooInst = Activator.CreateInstance(typeDef) as IFoo;
string msg = fooInst.GetMsg();
}
}
}
fooInst is null on the following line:
var fooInst = Activator.CreateInstance(typeDef) as IFoo;
What's interesting is when I debug the web page, I have a valid type definition in 'typeDef' variable and what is weird is that if I add Activator.CreateInstance(typeDef) as IFoo
to the Watch window in Visual Studio the result is not null!
What am I missing here?
P.S. - I've already verified that the assembly(TestClassLib.dll) is present in the bin directory of the ASP.NET app.