2

I have a console application in which I declared a class which is defined under a namespace. I want to create an instance of that class at runtime using assemblyname and class name. I tried the below code

var objAssembly = Assembly.Load(assemblyName);
var objType = objAssembly.GetType(className);
var obj = Activator.CreateInstance(objType);

But it is not working. Below is the class structure

namespace ReportService.ReportWriters
{
    class ExcelWriter : IReportWriter
    {
    }
}

I passed assembly name = ExcelWriter class name = ReportService.ReportWriters

7
  • 2
    Could you be more specific about the "it's not working" part? Commented Aug 18, 2015 at 12:03
  • The exception is - Could not load file or assembly 'ExcelWriter' or one of its dependencies. The system cannot find the file specified. Commented Aug 18, 2015 at 12:05
  • 1
    The part about "cannot find the file specified" is more or less self-explanatory, right? Commented Aug 18, 2015 at 12:06
  • I updated my question.Please check it Commented Aug 18, 2015 at 12:09
  • Is ExcelWriter.dll signed? Is it in the directory from which your program is started? Does it have dependencies? Commented Aug 18, 2015 at 12:14

2 Answers 2

2

Maybe tou should get all types and find ExcelWriter class and initialize it:

var objAssembly = Assembly.Load(assemblyName);
var objType = objAssembly.GetTypes().First(x => x.Name == "ExcelWriter");
var obj = Activator.CreateInstance(objType);

Or use Assembly.CreateInstance() method:

var namespaceName = "ReportService.ReportWriters";
var objAssembly = Assembly.Load(assemblyName);
var obj = objAssembly.CreateInstance(objAssembly.GetName().Name.Replace(" ","_") + "." + namespaceName + "." + "ExcelWriter");

NOTE: If assemblyName contains spaces compiler converts spaces to _ character.

NOTE: Add using System.Linq; to usings.

Sign up to request clarification or add additional context in comments.

4 Comments

I tried both condition.Is not working.Giving exception "Could not load file or assembly 'ExcelWriter' or one of its dependencies. The system cannot find the file specified."
What returns objAssembly.GetTypes() method at your code?
Assembly.Load(assemblyName); is giving exception mentioned above. The dll is not there in bin folder.Is this causing the issue?
Try Assembly.FromFile() method and give it your assembly file location.
0

Yes, because your class does not contain any public or internal default constructor.

create public default constructor and then try, It should work normally.

Check this article -

https://msdn.microsoft.com/en-us/library/wccyzw83(v=vs.110).aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.