Jul 28, 2009

Raise Event from outside

Normally raising event is the responsibility side of a class, but in workflow there is a need to raise event from outside. Here is the code that allow client dynamically raise event externally.

class EventRaiser
    {
        static BindingFlags getEventFlags = BindingFlags.Instance | BindingFlags.NonPublic;
        private object _eventObject;
        private MethodInfo _eventInvoker;

        public EventRaiser(object hostingObject, string eventName)
        {
            FieldInfo fieldInfo = hostingObject.GetType().GetField(eventName, getEventFlags);
            _eventObject = fieldInfo.GetValue(hostingObject);
            _eventInvoker = _eventObject.GetType().GetMethod("Invoke");
        }

        public void RaiseEvent(WorkflowEventArguementBase argument)
        {
            _eventInvoker.Invoke(_eventObject, new object[] { null, argument });
        }
    }