Link: How can dynamic be used as generic?
public void CheckEntity(int entityId, string entityType = null) { dynamic AnyObject = Activator.CreateInstance("Assembly","Assembly.Models.DbModels." + entityType).Unwrap(); CheckWithInference(AnyObject, entityId); } private static void CheckWithInference<T>(T ignored, int entityId) where T : class { Check<T>(entityId); } private static void Check<T>(int entityId) where T : class { using (var gr = new GenericRepository<T>()) { } }
Included with CheckEntity(16,"Container"); . After the first line is AnyObject becomes empty Assembly.Models.DbModels.Container when checking with the debugger. If var AnyType = AnyObject.GetType(); used var AnyType = AnyObject.GetType(); , then AnyType displayed as Assembly.Models.DbModels.Container . However, when calling CheckWithInference(AnyObject, entityId); an exception is thrown.
external: the reference to the object is not installed in the instance of the object. inner: Microsoft.CSharp.RuntimeBinder.SymbolTable.GetOriginalTypeParameterType (Type t) +10
Here I made an independent example, but it works without errors :(
Please note that this is in asp.net mvc 3 c #
HomeController.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace InferenceExample.Controllers { public class HomeController : Controller {
Example.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace InferenceExample.Models { public class Example { public int ExampleId { get; set; } public string Name { get; set; } } }
Index.cshtml
@{ ViewBag.Title = "Index"; } <h2>Index</h2> @Html.ActionLink("Start", "CheckEntity", new { entityId = 16, entityType = "Example" })
I'm at a loss. Why am I getting this exception? I could not easily reproduce it. I'm not sure what else needs to be included for the example, since that is all that the actual code has in it.
Actually, the confusing part is that in the application, when this exception occurs, the action is not performed. However, when you re-view the page and repeat the second time, there is no exception.