jeudi 17 novembre 2016

Create type by runtime type info using Activator

Intro

To create instances on the fly via reflection, we could use:

Activator.CreateInstance 

The downside to this is that this returns an object, while I really need the concrete type and since I only know the runtime type I can't cast.

To accomplish this, we can use

Activator.CreateInstance<T>

Which returns a T, but since I don't know T at compile time, this is no use either. At first glance anyway.

Currently I'm using dynamic for this:

// I know for sure the
dynamic concreteType = Activator.CreateInstance(runTimeType);

Before this line some sanity checks are performed. For example I know the runtime type is always a certain ITopSecretObject at this point, otherwise the statement can't get hit.

So presumably this is reasonably safe. It does exactly what I want, with 1 line of code, which seems great.

However I'm not sure this is the intended way of using dynamic and if I'm setting the door open for nasty stuff.

Why do I want this

Currently we have 1000s of lines of boilerplate code in many Update methodes across various services. This is handcrafted, thus error-prone, repetetive, violates DRY and makes it harder for new people. Furthermore this makes the methods unclear by losing focus on business logic and, frankly, is just plain ugly. All the usual suspects ;)

So I'm writing some abstract/generic code to factor out all that repetitive stuff. Which is a very nice and cool bit of software to write, but leaves me with (mostly) runtime info.

Under the surface these methods all use Entity Framework and its ApplyCurrentValues method. This method requires a concrete, instantianted, type and hence my questions.

Hope this is clear enough :)

Questions

  • Is this an OK way to use dynamic, considering I perform do some sanity checks before actually using it?
  • I feel that there's a way using reflection to accomplish this. That might be worse in terms of performance, but I'm very curious if this can be done. Is it possible to create the generic Activator.CreateInstance<T> using reflection?
  • Are either possibilities bad and should I take a different approach entirely? However not knowing the concrete types at run-time, but needing them anyway is not something I can move away from.




Aucun commentaire:

Enregistrer un commentaire