There is a piece of .net C# code which use Reflection to create an instance using Activator.CreateInstance()
. This is an old piece of code and runs on the top of Enterprise Library. Is it a better idea to replace this with Dependency Injection to create objects? Is there any Pro’s and Con’s for either approach?
1
It probably depends on a number of questions:
- How many instances of the object do you create at runtime? If there is a small finite number I would tend towards DI, if there are a large number at different times I would tend towards reflection
- What arguments does the objects constructor take? If they vary at runtime then reflection may be better but if they are always known up front then you may be better using DI.
- What is wrong with the current implementation? Does it not meet requirements, is it hard to support, or are you just refactoring? What would you like to achieve and would DI help in those goals?
It’s also worth pointing out that DI frameworks will just use reflection under the hood anyway to create objects at runtime.
As a general approach I think that you can replace a code that use Activator.CreateInstance
with a Factory
. The factory can accept a parameter that you can use to select the correct type to create and then resolve that type using the IoC container.
For example Castle Windsor as a feature called Typed Factory that can do all the work for your.
For example if you have the following code:
var component = (MyService)Activator.CreateInstnace(myImplementationType, [params]);
You can replace with something like
var component = myFactory.Create(params);
or
var component = myFactory.Create<MyService>([params]);
Another approach that can be used is to invert the dependency (Inversion of Control) and let the main component decides what components to inject. This is the recommended approach in most situations. From the main you can register the correct implementation and let the Dependency Injection do it’s work.
1