Sorangwala Abbasali Sorangwala Abbasali - 3 months ago 17
C# Question

How to access a private constructor from controller to model class in mvc 4

Is there any way to access a private constructor from controller to model?

The controller containing method calling the model is as follows:

public ActionResult ReadXML()
{
XmlSerializer reader = new XmlSerializer(typeof(List<Asseted>));
TextReader textReader = new StreamReader(@"D:\Tial2.xml");
List<Asseted> asseted;
List<Asseted> list = new List<Asseted>();
asseted = (List<Asseted>)reader.Deserialize(textReader);
textReader.Close();
for (int i = 0; i < asseted.Count; i++)
{
string data123 = Convert.ToString(asseted[i].PopertyValue);
string data234 = Convert.ToString(asseted[i].PropertyName);
list.Add(new Asseted(data123,data234));

}
return View();
}


The model containing the Method to be called is as follows:

[XmlRoot]
public class Asseted
{
string pName, pValue;
private string data234;
private string data123;

private Asseted(string data234, string data123)
{
// TODO: Complete member initialization
PropertyName = data234;
PopertyValue = data123;
}
[XmlElement]
public string PropertyName { get; set; }

[XmlElement]
public string PopertyValue { get; set; }
}

Answer

Is there any way to access a private constructor from controller to model?

While it may be arguable if this is the right way to solve your problem, the question itself can be answered with YES. And it's not even very hard with reflection.

ConstructorInfo constructor = typeof(Asseted).GetConstructor(
    BindingFlags.NonPublic | BindingFlags.Instance, 
    null, 
    new[] { typeof(string), typeof(string) }, 
    null);

Asseted instance = constructor.Invoke(new[] { 
    "data234", 
    "data123" 
}) as Asseted;

Basically you get the type (Asseted), get the constructor that matches your known parameter types and invoke it. Done.

Additional Note: Depending on your compiler and actual code, you might run into a TypeAccessException.