Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
1  
A piece of surrounding code where you use Activator.CreateInstance() would help illustrate your question. –  CodeCaster Nov 9 '13 at 11:27

2 Answers 2

up vote 2 down vote accepted

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.

share|improve this answer

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.

share|improve this answer
1  
I guess you don't mean "replace", you mean "refactor the code to move the CreateInstance into a factory method." But what makes you assume the code calling CreateInstance is not already part of a factory? The OP posted far too few information to know that. –  Doc Brown Nov 9 '13 at 12:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.