Working on a page where I create new instances of a usercontrol I wrote, based on data. I pass in filtered data to the user control using constructor injection. However, when the user controls render, only the last set of data injected in is rendered for all user controls. It appears I'm referencing the same instance rather than creating a new, independent one. Ideas?
protected void Page_Init(object sender, EventArgs e)
{
var data = <my data comes from here>;
var yearsInData = data.OrderByDescending(x=>x.Year).Select(x => x.Year).Distinct();
foreach(var year in yearsInData)
{
var employers = data.OrderBy(x=>x.EmployerName).Where(x => x.Year == year).Select(x => x.EmployerName).Distinct();
foreach (var employer in employers)
{
var eob = data.Where(x => x.Year == year).Where(x => x.EmployerName == employer);
if (eob.Count() > 0)
{
var ctl = LoadControl(@"~\Shared\Controls\AnnualEOBControl.ascx", eob);
pnlMain.Controls.Add(ctl);
}
}
}
}
Here is the LoadControl method:
private UserControl LoadControl(string userControlPath, params object[] constructorParameters)
{
var constParamTypes = new List<Type>();
foreach (var constParam in constructorParameters)
{
constParamTypes.Add(constParam.GetType());
}
var ctl = Page.LoadControl(userControlPath) as UserControl;
// Find the relevant constructor
if (ctl != null)
{
var constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray());
// And then call the relevant constructor
if (constructor == null)
{
throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType);
}
constructor.Invoke(ctl, constructorParameters);
}
// Finally return the fully initialized UC
return ctl;
}