user366312
user366312

Reputation: 17006

C# Reflection Utility

I have written the following Utility class to get an instance of any class of name "className".

public class AssemblyUtils
    {
        private AssemblyUtils()
        {
        }

        public static T GetInstance<T>(string assemblyName, string className)
        {
            T classInstance = default(T);

            System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(assemblyName);

            object o = assembly.CreateInstance(className);

            if (o is T)
            {
                classInstance = (T)o;
            }
            else
            {
                o = null;
            }


            return classInstance;
        }

I have called this like:

IMyInterface ins = AssemblyUtils.GetInstance<IMyInterface>(@"MyNamespace.DA.dll", "MyClassDA");

But I am getting the following error message:

Could not load file or assembly 'MyNamespace.DA.dll' or one of its dependencies. The system cannot find the file specified.

Note that, I called the AssemblyUtils.GetInstance() from separate assemblies which are in the same sln.

How can I resolve the assembly path???

Upvotes: 1

Views: 1934

Answers (4)

Vadim
Vadim

Reputation: 21714

My guess is that it cannot find assembly because it's not in the same folder and not in the GAC, or other directories where the system is looking for.

You need either move them in the same folder where an executing assembly. You can change the folder where assembly is loaded from by using AppDomainSetup.PrivateBinPath Property.

Upvotes: 5

Mike Two
Mike Two

Reputation: 46203

As Vadim mentioned Assembly.Load will only look in a limited set of places. Assembly.LoadFrom might be a better bet for you. It takes a path (with filename) to the assembly.

Assembly.Load works off the assembly name, not the path.

Upvotes: 1

George Mauer
George Mauer

Reputation: 122202

Check your bin\Debug folder, is the MyNamespace.DA.dll in that folder? If not you're going to have to move it in there manually. Maybe add a postcondition so that its copied in automatically. Also try using the full assembly strong name.

Also JMSA, how about some upvotes and accepting answers on your other thread?

Upvotes: 1

Canavar
Canavar

Reputation: 48098

I think, the assembly you want to load (MyNamespace.DA.dll) is dependent to another assembly which is not located in you folder you're looking for. Copy the dependent assemblies into the folder where you located MyNamespace.DA.dll assembly.

Upvotes: 1

Related Questions