How to Load Assembly at Runtime and Create Class Instance

How to load Assembly at runtime and create class instance?

If your assembly is in GAC or bin use the assembly name at the end of type name instead of Assembly.Load().

object obj = Activator.CreateInstance(Type.GetType("DALL.LoadClass, DALL", true));

Loading assemblies at runtime and creating instances using Activator.CreateInstance()

You have to first load the assembly into your current AppDomain:

AppDomain.CurrentDomain.Load(File.ReadAllBytes(assemblyFileName));

EDIT: Does this work?

Form form = (Form)Activator.CreateInstance(Type.GetType(typeName))

Correct Way to Load Assembly, Find Class and Call Run() Method

Use an AppDomain

It is safer and more flexible to load the assembly into its own AppDomain first.

So instead of the answer given previously:

var asm = Assembly.LoadFile(@"C:\myDll.dll");
var type = asm.GetType("TestRunner");
var runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

I would suggest the following (adapted from this answer to a related question):

var domain = AppDomain.CreateDomain("NewDomainName");
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

Now you can unload the assembly and have different security settings.

If you want even more flexibility and power for dynamic loading and unloading of assemblies, you should look at the Managed Add-ins Framework (i.e. the System.AddIn namespace). For more information, see this article on Add-ins and Extensibility on MSDN.

Create object from dynamically load assembly and cast it to interface (.NET 2.0)

You need to somehow make .NET to load the assemblies to the same context to be able to do a cast between the types in those assemblies.

1- Put the assembly in the application path or GAC so that the Load (not the LoadFrom) function will find it.

2- Create an app domain and do all of the work there. You can fully control where the assemblies are being searched for an app domain.

3- Use the add-in model.

Read this article to learn more about your options: Best Practices for Assembly Loading

dynamically create class object by using assemblyname and type of class

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.

Load Assembly and create class using Reflection

You need to do two things:

1) Convert your string str into a type, and
2) Create an instance of that type.

string typeString = "My.Assembly.Namesapce.MyClass, My.Assembly.Namesapce, Version=4.0.0.0, Culture=neutral, PublicKeyToken=84474dc3c6524430";

// Get a reference to the type.
Type theType = Type.GetType(typeString, true, false);

// Create an instance of that type.
MyClass theInstance = (MyClass)Activator.CreateInstance(theType);

How to create dynamic instance of assembly ( C# ) and loading the dependencies of instance assembly dynamically as well?

Finally I found solution for my problem.

This is what worked for me. Perfect and what I was looking for !! :)

static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

var implementor = string.Concat(Directory.GetCurrentDirectory(), @"\Implementations\Calculator.dll");
var implementorBytes = File.ReadAllBytes(implementor);

AppDomain.CurrentDomain.Load(implementorBytes);

Console.WriteLine(GetObject<IAdd>().SumNew(2, 2));
Console.WriteLine(GetObject<IAdd>().SumNew(2, 5));
}

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var dependencyResolverBaseDirectory = string.Concat(Directory.GetCurrentDirectory(), @"\Implementations");

return Directory.GetFiles(dependencyResolverBaseDirectory, "*.dll")
.Select(Assembly.LoadFile)
.FirstOrDefault(assembly => string.Compare(args.Name, assembly.FullName, StringComparison.CurrentCultureIgnoreCase) == 0);
}

public static T GetObject<T>()
{
var t = typeof(T);

var objects = (
from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetExportedTypes()
where typeof(T).IsAssignableFrom(type) && (string.Compare(type.FullName, t.FullName, StringComparison.CurrentCultureIgnoreCase) != 0)
select (T)Activator.CreateInstance(type)
).ToList();

return objects.FirstOrDefault();
}


Related Topics



Leave a reply



Submit