I have a project, which loads implementations using MEF with the following structure:
MyProject
|
| (Imports with MEF)
|
MyImplementation
|
| (has reference to)
|
ThirdPartyLib
/ \
/ \ (has refs to)
/ \
USB.dll Bluetooth.dll
When I try to import MyImplementation
on my development / testing machine - Windows 11 - it works fine.
However, on a user's machine (Windows 10, build 1607) I get the following exceptions:
System.TypeLoadException: Could not find Windows Runtime type 'Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicsResult'.
System.TypeLoadException: Could not find Windows Runtime type 'Windows.Devices.Bluetooth.GenericAttributeProfile.GattDescriptorsResult'.
System.TypeLoadException: Could not find Windows Runtime type 'Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceServicesResult'.
A quick lookup of one of these types shows it was only introduced as of Win 10 Build 15063, which explains the exception on 1607 - which is fine, because I don't actually use the bluetooth functionality (I'm assuming these 3 types are used by the Bluetooth.dll
. In fact, if I use a sample app that has a direct reference to ThirdPartyLib
it works fine without any exceptions.
I only have control over the code for MyProject
and MyImplementation
. Is there a way of allowing either of these (preferably in MyImplementation
) to ignore specific exceptions so that MEF can compose the parts anyway?
(Alternatively, I'd be as happy if it was possible to include another lib that would fill in the gaps of those missing types - but not sure if this is possible either).
I resolved this by removing the reference from my MyImplementation
to ThirdPartyLib
and then using Reflection to load it and resolve the types, properties & methods I needed.
private object _tpClass;
private Type _tpType;
private Assembly _tpAssembly;
public MyImplementation()
{
_tpAssembly = Assembly.LoadFrom(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"ApiLib", @"ThirdPartyAssembly.dll"));
_tpType = _wbpAssembly.GetType(@"ThirdPartyAssembly.ThirdPartyAssembly");
_tpClass = Activator.CreateInstance(_tpType, "myparam");
}
public string GetSomeInfo()
{
var method = _tpType.GetMethod("Get3partyResult");
var result = method.Invoke(_tpClass, null);
return result.GetType().GetProperty(@"TheData").GetValue(result);
}
and so on.
Feels like a bit of a hack and the code is a bit messy (and probably inefficient), but for MEF composing the parts, it's a case of out of sight, out of mind as far as the missing dependency is concerned.
Note that I had to put the ThirdPartyLib and its associated dlls in a subdir - i.e. not in the same dir as MyImplementation
and the other implementations being composed, or else I got the same exceptions above.
Just as an aside - ChatGPT suggested handling the AssemblyResolve
event and just returning null. This didn't work for me - it did get fired for the missing dependencies but I still got the exception.