segfault
segfault

Reputation: 5939

How to load DLL and create a new instance in C#?

I want to load a DLL file if it exists, and create a new instance of it, cast it and pass to another function.

What I currently do is to add a reference to the DLL, and create an instance, e.g.,

ConfigFileSystemRegistry.Instance.RegisterFileSystem("er://", new Efs());

I tried to load it dynamically, but it's giving a System.TypeInitializationException

My code used is:

        if (File.Exists("plugin\\Efsystem.dll"))
        {
            Assembly assembly = Assembly.LoadFrom("plugin\\Efsystem.dll");
            Type type = assembly.GetType("Efs");
            ConfigFileSystemRegistry.Instance.RegisterFileSystem("er://", (IFileSystem) Activator.CreateInstance(type));
        }

Upvotes: 0

Views: 856

Answers (2)

leppie
leppie

Reputation: 117220

System.TypeInitializationException implies your static constructor is throwing an exception. Check the inner exception and the stack trace for hints.

Upvotes: 1

Evren Kuzucuoglu
Evren Kuzucuoglu

Reputation: 3885

You might want to check the existence of a default constructor. If there isn't, see what arguments you need, and call the override of CreateInstance with the params object[] args argument.

Upvotes: 0

Related Questions