I'm trying to create a class using Activator.CreateInstance(assemblyName, typeName)
but I am getting the error
An unhandled exception of type 'System.TypeLoadException' occurred in mscorlib.dll
Additional information: Could not load type 'Question' from assembly 'AssessmentDeepCompare, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
In this example (which generates the error above) I'm trying to instantiate Question
which inherits from IAssessmentObject
and is in the same assembly.
public IAssessmentObject getInstance(string typeName) {
string assemblyName = Assembly.GetAssembly(typeof (IAssessmentObject)).ToString();
return (IAssessmentObject)Activator.CreateInstance(assemblyName, typeName);
}
What is the proper way to instantiate an object when you only have the Type name without the namespace or assembly?
It sounds like you do have the assembly - just not the namespace-qualified type name.
You can fetch all the types in the assembly, and get the type from that:
var type = typeof(IAssessmentObject).Assembly
.GetTypes()
.Single(t => t.Name == "Question");
var instance = (IAssessmentObject) Activator.CreateInstance(type);
If you have the assembly name and the type name, as well as the folder they live in, you can do this. I built this to return a logging class based on choices in the config file.
string _assemblyName = ConfigurationManager.AppSettings["MailLogger.AssemblyName"];
string _className = ConfigurationManager.AppSettings["MailLogger.ClassName"];
string _assemblyPath = ConfigurationManager.AppSettings["Reporting.Assembly.Folder"];
if (string.IsNullOrWhiteSpace(_assemblyName) || string.IsNullOrWhiteSpace(_className))
throw new ApplicationException("Missing configuration data for the Logger.");
Assembly _loggingAssembly = Assembly.LoadFrom(System.IO.Path.Combine(_assemblyPath, _assemblyName));
ILogger _logger = _loggingAssembly.CreateInstance(_className) as ILogger;
if (_logger == null)
throw new ApplicationException(
string.Format("Unable to instantiate ILogger instance from {0}/{1}", _assemblyName, _className));
return _logger;
If you don't have the assembly name, I'm not sure how would create it via reflection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With