mardi 4 août 2015

Dependency Injection, Parameter Type Compile Error

I've been working on a basic Inversion of Control Container in C#. I'm keeping it as simple as possible, using a Dictionary to store registered types. However, when I try to write my Resolve function, I get a compiler error.

private object RecursiveResolve<I>()
{
   // Find out what parameters we need for the object
   ConstructorInfo typeConstructor = typeof(I).GetConstructors().First<ConstructorInfo>();
   ParameterInfo[] typeParameters = typeConstructor.GetParameters();
   List<object> resolvedParameters = new List<object>();

   // Iterate through parameters
   foreach (ParameterInfo parameter in typeParameters)
   {
       Type parType = parameter.ParameterType;
       object resolvedParameter = RecursiveResolve<parType>(); // Compiler error here
       resolvedParameters.Add(resolvedParameters);
   }

   return typeConstructor.Invoke(resolvedParameters.ToArray());
}

The compiler error is: The type or namespace name parType could not be found (are you missing a using directive or an assembly reference)

My current thought about what's wrong is that RecursiveResolve expects a defined type name in the <>, and not a variable, even if the variable is a Type object. However, I'm not quite sure what the solution to this would be.

What would I need to change to keep parType, so that I can dynamically go through the parameters of an object and resolve them?





Aucun commentaire:

Enregistrer un commentaire