.netlambdaactivatorcreateinstance

.net compiled expressions instead of activator.createinstance()


I scan my assemblies looking for a specific types typeof(MyInterface<>) I then add these types to a static dictionary so that I can create instances of these types when requested.

I am creating these types using Activator.CreateInstance. But then I noticed the bad performance and research pointed me to http://mattgabriel.co.uk/2016/02/12/215/

Now, what I do is, store the compiled lambda in the dictionary

static IDictionary<string, Delegate> Store = new ConcurrentDictionary<string, Delegate>();

Where I am stuck is that when I get the delegate to create the instance by

Delegate instanceToCreate = DelegateStore.Store["keyName"];

Then I need to call the delegate which will create the instance by passing the parameter _configuration to the constructor. I tried;

instanceToCreate.DynamicInvoke(new object[] { _configuration });

The error I get is:

Object of type 'Microsoft.Extensions.Configuration.ConfigurationRoot' cannot be converted to type 'System.Object[]'.

What might be the problem?


Solution

  • The problem was with the "Delegate". Instead I used the concrete type;

    _store = new ConcurrentDictionary<string, Creator>();
    

    this allowed me to just call the constructor as;

    var createMe = store["creatorkey"]
    createMe(param1,....)