how to load dependent assembly?

2019-05-04 07:33发布

问题:

I have a project Processor and it depend on other 2 projects.

When i compile project I get dll Processor.dll and other project's depend dll in Bin folder. Processor.dll BusinessAction.dll and Repository.dll.

I tried to call method from Processor.dll by initiating type ProcessRequest class.

Like this

 Assembly processorAssembly = Assembly.LoadFile(path + "Processor.DLL"));

        Type myType= processorAssembly.GetType("Namespace.ProcessRequest");

        myType.InvokeMember("Process", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, submitOfferType, new object[] { 12345 });

Process method has some logic to process and save it to database.

when i invoke procee method using InvokeMember()

i get exception Could not load file or assembly 'Namespace.BusinessAction, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

I do i invoke method?

回答1:

Appdomain has an event which is fired if it can't find a reference:

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

In the event handler you can search for the assembly manually:

Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string s = @"C:\lib\" + args.Name.Remove(args.Name.IndexOf(',')) + ".dll";
    return Assembly.LoadFile(s);
}


回答2:

try

Assembly processorAssembly = Assembly.LoadFrom(path + "Processor.DLL")); 

this will load all supporting DLLs



标签: c# reflection