Reputation: 2468
I created a plug-in for a software which changes frequently. I want my plug-in to work with every new version of the main software. That is why I load the dependencies (which is the executable of the main software) for my plug-in short before creating the plug-ins' main object via reflection.
However this does not always work: I have a timing problem. The DLL is sometimes not loaded (completely) but the code to create the main object is executed. This trows an exception that a dependency is missing.
How do I wait for the DLL to load completely before creating my object?
class PluginStarter
{
private MainPluginObject mainPluginObject = null;
public PluginStarter()
{
AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) =>
{
var fullAssemblyName = new AssemblyName(eventArgs.Name);
if (fullAssemblyName.Name.Equals("MainSoftware"))
{
var found = Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, AppDomain.CurrentDomain.FriendlyName));
return found;
}
else
{
return null;
}
};
Initialize();
}
private void Initialize()
{
mainPluginObject = new MainPluginObject();
}
public void ShowForm()
{
mainPluginObject.ShowForm();
}
public void Dispose()
{
mainPluginObject.Dispose();
}
}
As soon as I deactivate in-lining for the Initialize()
method with [MethodImpl(MethodImplOptions.NoInlining)]
it just works.
Is removing in-lining the correct solution here?
What else can I do if there are no events in Assembly
informing you about the DLL load status?
Upvotes: 1
Views: 1002
Reputation: 16067
If your method is in-lined, then the dll will be needed and hence loaded before your PluginStarter constructor is called (when the method is being compiled) and in particular that means before your AssemblyResolve event has been initialised.
So either you either need to make sure that Initialize isn't in-lined, or else put your AssemblyResolve code in a static constructor.
Using a static constructor would probably be cleaner as it will only create one event regardless of how many PluginStarter objects are created.
Upvotes: 1