ekonbenefits / impromptu-interface

Static interface to dynamic implementation (duck casting). Uses the DLR combined with Reflect.Emit.
Apache License 2.0
657 stars 67 forks source link

Issue Loading Type Dynamically #44

Closed LuvForAirplanes closed 3 years ago

LuvForAirplanes commented 3 years ago

I'm getting his exception when I try to dynamically get a type:

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Failure has occurred while loading a type.
System.TypeLoadException: Failure has occurred while loading a type.
   at System.Reflection.Emit.TypeBuilder.CreateTypeInfo()
   at ImpromptuInterface.Build.BuildProxy.BuildTypeHelper(ModuleBuilder builder, Type contextType, Type[] interfaces) in C:\Users\Micah\Downloads\impromptu-interface-master\impromptu-interface-master\ImpromptuInterface\src\EmitProxy\BuildProxy.cs:line 400
   at ImpromptuInterface.Build.BuildProxy.BuildType(Type contextType, Type mainInterface, Type[] otherInterfaces) in C:\Users\Micah\Downloads\impromptu-interface-master\impromptu-interface-master\ImpromptuInterface\src\EmitProxy\BuildProxy.cs:line 148
   at ImpromptuInterface.Impromptu.DynamicActLike(Object originalDynamic, Type[] otherInterfaces) in C:\Users\Micah\Downloads\impromptu-interface-master\impromptu-interface-master\ImpromptuInterface\src\Impromptu.cs:line 159
   at WebApplication1.DIService.ResolveCustomersService() in C:\Users\Micah\Downloads\impromptu-interface-master\impromptu-interface-master\WebApplication1\rvice.cs:line 31
   at WebApplication1.Pages.Index.OnAfterRender(Boolean firstRender) in C:\Users\Micah\Downloads\impromptu-interface-master\impromptu-interface-master\WebApplication1\Pages\Index.razor:line 28
   at Microsoft.AspNetCore.Components.ComponentBase.Microsoft.AspNetCore.Components.IHandleAfterRender.OnAfterRenderAsync()
   at Microsoft.AspNetCore.Components.Rendering.ComponentState.NotifyRenderCompletedAsync()

The exception occurs on this line: https://github.com/ekonbenefits/impromptu-interface/blob/master/ImpromptuInterface/src/EmitProxy/BuildProxy.cs#L399

And here is my code:

var type = typeof(ICustomersService);
var expando = new ExpandoObject() as IDictionary<string, object>;
//expando population code here
dynamic myInterface = Impromptu.DynamicActLike(expando, type.GetType());

The reason I have to do type.GetType(), is because the type handed into the method could be anything.

@jbtule is this a bug?

jbtule commented 3 years ago

You have type inception. type.GetType() is equivalant to typeof(ICustomersService).GetType() , you end up getting the type of types. you want Impromptu.DynamicActLike(expando, type );

LuvForAirplanes commented 3 years ago

Oh, gotcha!!! Wow, I thought I knew C# until I started dabbling in the underlying type system and reflection...