Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateInstance from Type name and Assembly name

Tags:

c#

reflection

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?

like image 382
bflemi3 Avatar asked Sep 01 '25 05:09

bflemi3


2 Answers

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);
like image 59
Jon Skeet Avatar answered Sep 02 '25 19:09

Jon Skeet


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.

like image 41
Maurice Reeves Avatar answered Sep 02 '25 17:09

Maurice Reeves