I'm trying to load an assembly with the AssemblyLoadContext
(exists from the version 3.0 of netcore), instantiate an object and cast this object to an interface, but I get a cast exception error.
The interface is shared between the project that loads the assembly and the implementation instantiated. The object apparently is instantiated correctly but I get the unexpected error when I do (T)instance
.
Trying with watcher I'm able to cast the instance correctly to the interface, following the code I'm using and a screenshot of the watcher:
private (ExecutionAssemblyLoadContext, T) LoadTheAssemblyAndInstance<T>(string assemblyName, string typeNameToInstance)
{
var basePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var assemblyContext = new ExecutionAssemblyLoadContext($"{basePath}/{assemblyName}.dll");
var assembly = assemblyContext.LoadFromAssemblyPath($"{basePath}/{assemblyName}.dll");
var externalCodeEvent = typeNameToInstance != null ? assembly.ExportedTypes
.Where(x => x.FullName == typeNameToInstance)
.Single() : assembly.ExportedTypes.First();
var instance = Activator.CreateInstance(
externalCodeEvent,
_defaultConstructorParameters
);
return (assemblyContext, (T)instance);
}
this is the full exception message:
System.InvalidCastException: 'Unable to cast object of type 'Expriva.NewWorkflow.BPMN.ExecutionCodeTest.ExecutionContractTest' to type 'Expriva.NewWorkflow.ExternalShared.Interfaces.IExecutionContract'.'
Following a screenshot that shows that T
is implemented by the instance:
Sample code
An example repository has been added on GitHub to make it easier to see and test what the problem is. It would be great to have a way to use the type (interface of other) transparently either if it is loaded from AssmemblyLoadContext or not.
T
– SacramentExecutionContractTest
does not implementIExecutionContract
. Please make sure it does. – Sacrament