Here is a more practical example. I want to instantiate a ObjectMaterializedEventArg
from Entity Framework. It looks like this:
namespace System.Data.Entity.Core.Objects
{
/// <summary>EventArgs for the ObjectMaterialized event.</summary>
public class ObjectMaterializedEventArgs : EventArgs
{
private readonly object _entity;
internal ObjectMaterializedEventArgs(object entity)
{
this._entity = entity;
}
/// <summary>Gets the entity object that was created.</summary>
/// <returns>The entity object that was created.</returns>
public object Entity
{
get { return this._entity; }
}
}
}
As we we see, this event arg sports only an internal constructor.
To make a unit test to a patient decrypting rule in the software system I work with, we need to instantiate such an object, so I ended up using the GetConstructors
method instead.
[Test]
public void EmptyNameAndOfficialIdDoesNotThrow()
{
var patientDecryptingRule = new PatientDecryptingRule();
object[] reservation = new object[]
{
new Operation
{
Status = (int) OperationStatusDataContract.Reservation,
Patient = new Patient
{
Name = null,
OfficialId = null,
IsPatientEncrypted = true
}
}
};
var relevantConstructor = typeof(ObjectMaterializedEventArgs).GetConstructors(
BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault();
ObjectMaterializedEventArgs objectMaterializedEventArgs =
(ObjectMaterializedEventArgs) relevantConstructor?.Invoke(reservation);
patientDecryptingRule.ModifyObjectMaterialized(objectMaterializedEventArgs);
}
I use GetConstructors
here, specifying that the constructor to look for is non public (internal for example) and instance as bindingflags
, then use FirsOrDefault
.
Hope this scenario is helpful to some that have trouble getting GetConstructor
correct. You can use GetConstructors
instead and filter some more if necessary. Then in the ?.Invoke()
pass in the object array of your parameters.