I'm trying to build an infrastructure which by reflection - provides the needed objects. so far things works good, except for a case where registration to event of an injected service did not work well, and I can't invoke this event. some code: the infrastructure where the instantiation occurs:
public ViewModelBase CreateWidget(string viewModelName)
{
List<object> args = new List<object>();
Type viewModelType = widgetTypes.FirstOrDefault(type => type.Name == viewModelName);
var ctors = viewModelType.GetConstructors();
if (ctors == null || ctors.Count() < 1)
{
return null;
}
var ctor = ctors.FirstOrDefault();
//Get the constructor arguments and instantiate the services (for injection)
foreach (var param in ctor.GetParameters())
{
//Get the constructor's argument
Type objectType = param.ParameterType;
var descendantType = servicesTypes.FirstOrDefault(p => objectType.IsAssignableFrom(p));
Assembly businessAssembly = descendantType.Assembly;
//instantiate the services
object service = GetInstance(businessAssembly, descendantType, null);
args.Add(service);
}
Assembly assem = viewModelType.Assembly;
ViewModelBase viewModel = null;
//instantiate a class and injecting it the service
object viewModelObj = GetInstance(assem, viewModelType, args.ToArray());
viewModel = (ViewModelBase)viewModelObj;
viewModel.RegisterToServicesEvents();
return viewModel;
}
private object GetInstance(Assembly assembly, Type objectType, object[] arguments)
{
try
{
return assembly.CreateInstance(objectType.FullName, true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
BindingFlags.CreateInstance | BindingFlags.InvokeMethod, null, arguments, CultureInfo.CurrentUICulture, null);
}
catch (ArgumentNullException ex)
{
Debug.WriteLine($"Exception has been found : {ex.Message}");
}
catch (MissingMethodException exm)
{
Debug.WriteLine($"MissingMethodException has been found : {exm.Message}");
}
return null;
}
#endregion
}
as it can be seen, after initializing the class, a method RegisterToServicesEvents is called and registring to events on the injected service is occur. and there's the problem: when tring to invoke the event on service, it looks like no object have registered to it. (I thought it probably related to late binding in the creation by reflection, but I changed the registration to the event to be only after the creation.... so) where I'm I doing wrong?
Aucun commentaire:
Enregistrer un commentaire