vendredi 6 février 2015

Cannot instantiate object using reflection/Assembly/Activator in c# from a string

I have a namespace that defines a class (I'll omit the code):



namespace My.Business.Services
{
public class ProgressSender
{
}
}


This project is saved as a DLL.


In another project in my solution I try to instatiate it in various ways (in reality this is a string in my app.config) but they all fail (it does work explicitly creating the class early bound in code). I've included My.Business.Services as a reference to the program too:



namespace My.Progress.Imaging
{
static class Program
{
static void Main(string[] args)
{
string exportItemNS = "My.Business.Services";
string exportItemC = "ProgressSender";
string exportItemFull = "My.Business.Services.ProgressSender";

//value cannot be null
ProgressSender obj =
(ProgressSender)Activator.CreateInstance(Type.GetType(exportItemFull));

//could not load type 'ProgressSender' from assembly 'My.Business.Services'
var obj=Activator.CreateInstance(exportItemNS, exportItemC);

//could not load type 'ProgressSender' from assembly 'My.Business.Services'
ProgressSender s=(ProgressSender)Activator.CreateInstance(null, exportItemFull);

//Loads ok but then classType is null
Assembly assembly;
assembly = Assembly.Load(exportItemNS);
Type classType = assembly.GetType(exportItemC);

}
}
}


If I get a type from the same namespace or even System it's fine:



Type t = Type.GetType("My.Progress.Imaging.Program");
t = Type.GetType("System.String");





Aucun commentaire:

Enregistrer un commentaire