title: How can you generically map a DbDataReader to a Castle.Windsor resolved type?
body: <p>This is confusing me, so this question will probably be confusing.</p>
  
  <p>I have a an application that uses implementations of an IJob interface to accomplish different tasks. </p>
  
  <pre><code>public interface IJob
  {
    int Id { get; set; }
    string Name { get; set; }
    void Run();
  }
  </code></pre>
  
  <p>I am using the Castle.Windsor.WindsorContainer to resolve these implementations, and using the service id to help identify them.</p>
  
  <pre><code>WindsorContainer container = new WindsorContainer(new XmlInterpreter());
  IJob jobToExecute = container.Resolve&lt;IJob&gt;("nameOfJob");
  </code></pre>
  
  <p>I wrote a little generic extension method that simply puts the values of SQL columns into their corresponding properties. </p>
  
  <pre><code>    public static void MapTo&lt;T&gt;(this DbDataReader reader, ref T instance) where T : class
      {
          Type objectType = typeof(T);
  
          foreach (PropertyInfo propertyInfo in objectType.GetProperties())
          {
              if (propertyInfo.CanWrite)
              {
                  int ordinal = -1;
                  try
                  {
                      ordinal = reader.GetOrdinal(propertyInfo.Name);
                      object value = reader[ordinal] == DBNull.Value ? null : reader[ordinal];
                      propertyInfo.SetValue(instance, value, null);
                  }
                  catch (IndexOutOfRangeException ex)
                  {
                      continue;
                  }
  
              }
          }
      }
  </code></pre>
  
  <p>Now, because you can't instantiate an instance of an interface, passing an IJob to this method won't work. However, in order to gain the benefits of the IoC container, I need to do everything in my repository using the IJob interface. So, I wrote with this to resolve the IJob implementation, and pass it to the MapTo method to populate the necessary properties:</p>
  
  <pre><code>    public IJob GetJobById(int id)
      {
          string cmdTxt = "SELECT Id, Name, Description, DateStarted, ScheduledCompletion, Completed FROM Jobs WHERE Id = @id";
  
          using (DbCommand cmd = _dataFactory.CreateCommand(cmdTxt))
          {
              _dataFactory.AddParam(cmd, "id", id, DbType.Int32);
              using (DbDataReader rdr = cmd.ExecuteReader())
              {
                  if (rdr.Read())
                  {
                      IJob job = _container.Resolve&lt;IJob&gt;("job.implementation");
                      rdr.MapTo&lt;IJob&gt;(ref job);
                      return job;
                  }
                  else
                  {
                      return null;
                  }
              }
          }
      }
  </code></pre>
  
  <p>Is this an OK design decision? Do you see any problems?</p>