Beispiel #1
0
        public ObserverGrain()
        {
            GrainType = GetType();
            var handlerAttributes = GrainType.GetCustomAttributes(typeof(HandlerAttribute), false);

            if (handlerAttributes.Length > 0)
            {
                handlerAttribute = (HandlerAttribute)handlerAttributes[0];
            }
            else
            {
                handlerAttribute = default;
            }
            foreach (var method in GrainType.GetMethods())
            {
                var parameters = method.GetParameters();
                if (parameters.Length >= 1 &&
                    typeof(IEvent).IsAssignableFrom(parameters[0].ParameterType))
                {
                    var evtType = parameters[0].ParameterType;
                    if (parameters.Length == 2 && parameters[1].ParameterType == typeof(EventBase))
                    {
                        var dynamicMethod = new DynamicMethod($"{evtType.Name}_handler", typeof(Task), new Type[] { typeof(object), typeof(IEvent), typeof(EventBase) }, GrainType, true);
                        var ilGen         = dynamicMethod.GetILGenerator();//IL生成器
                        ilGen.DeclareLocal(evtType);
                        ilGen.Emit(OpCodes.Ldarg_1);
                        ilGen.Emit(OpCodes.Castclass, evtType);
                        ilGen.Emit(OpCodes.Stloc_0);
                        ilGen.Emit(OpCodes.Ldarg_0);
                        ilGen.Emit(OpCodes.Ldloc_0);
                        ilGen.Emit(OpCodes.Ldarg_2);
                        ilGen.Emit(OpCodes.Call, method);
                        ilGen.Emit(OpCodes.Ret);
                        var func = (Func <object, IEvent, EventBase, Task>)dynamicMethod.CreateDelegate(typeof(Func <object, IEvent, EventBase, Task>));
                        _handlerDict_1.Add(evtType, func);
                    }
                    else
                    {
                        var dynamicMethod = new DynamicMethod($"{evtType.Name}_handler", typeof(Task), new Type[] { typeof(object), typeof(IEvent) }, GrainType, true);
                        var ilGen         = dynamicMethod.GetILGenerator();//IL生成器
                        ilGen.DeclareLocal(evtType);
                        ilGen.Emit(OpCodes.Ldarg_1);
                        ilGen.Emit(OpCodes.Castclass, evtType);
                        ilGen.Emit(OpCodes.Stloc_0);
                        ilGen.Emit(OpCodes.Ldarg_0);
                        ilGen.Emit(OpCodes.Ldloc_0);
                        ilGen.Emit(OpCodes.Call, method);
                        ilGen.Emit(OpCodes.Ret);
                        var func = (Func <object, IEvent, Task>)dynamicMethod.CreateDelegate(typeof(Func <object, IEvent, Task>));
                        _handlerDict_0.Add(evtType, func);
                    }
                }
            }
        }