views:

290

answers:

4

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???

+5  A: 

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.

Vadim
PrivateBinPath can only be set to a folder under the application's base directory. It cannot be set to just any folder. So this will work as long as the assembly is somewhere in the folder hierarchy of application.
Mike Two
@Mike Two. Good point. Thanks for this clarification.
Vadim
+1  A: 

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.

Canavar
+1  A: 

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?

George Mauer
Ok buddy! You got it. But can you plz give me one up-vote also so that negative point is leveled?
JMSA
I thought your question was fair, already did it - it was at -2.
George Mauer
+1  A: 

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.

Mike Two