Some days ago I needed to write some tests for an old Windows Service. I was not authorized to make any changes in the Code of the Service (and its libraries), so in order to invoke some protected/private method I needed to use the reflection. What follows, is the code I used: nothing complicated, but maybe can save a bit of your time in case you need to achieve the same 🙂
The name of the method I needed to call is “OnStart”.
MethodInfo onStart = typeof(Service).GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Instance); if (onStart != null) { object result = null; ParameterInfo[] parameters = onStart.GetParameters(); object classInstance = Activator.CreateInstance(typeof(Service), null); var parameterType = parameters[0].ParameterType; object[] parametersArray = (object[])Activator.CreateInstance(parameterType, 1); result = onStart.Invoke(classInstance, parametersArray); }