示例#1
0
        private FieldReference CreateLoggerStaticField()
        {
            var logTypeRef = _typeReferenceProvider.LogAdapterReference;
            var logManagerTypeRef = _typeReferenceProvider.LogManagerReference;

            //look for existing one
            var loggerField = _typeDefinition.Fields.FirstOrDefault(fld => fld.IsStatic && fld.FieldType == logTypeRef);

            if (loggerField != null) return loggerField.FixFieldReferenceIfDeclaringTypeIsGeneric();

            //$log should be unique
            loggerField = new FieldDefinition("$log", FieldAttributes.Private | FieldAttributes.Static, logTypeRef);
            _typeDefinition.Fields.Add(loggerField);

            //create field init
            var staticConstructor = _typeDefinition.GetStaticConstructor();
            if (staticConstructor == null)
            {
                const MethodAttributes methodAttributes = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
                staticConstructor = new MethodDefinition(".cctor", methodAttributes, _typeReferenceProvider.Void);
                _typeDefinition.Methods.Add(staticConstructor);
                staticConstructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
            }

            var getLoggerMethod = new MethodReference("GetLogger", logTypeRef, logManagerTypeRef);
            getLoggerMethod.Parameters.Add(new ParameterDefinition(_typeReferenceProvider.Type));

            //build up typeInfo
            var getTypeFromHandleMethod = _methodReferenceProvider.GetGetTypeFromHandleReference();

            //spec treatment for generic types
            var loggerFieldRef = loggerField.FixFieldReferenceIfDeclaringTypeIsGeneric();

            //if generated nested type use the declaring type as logger type as it is more natural from
            //end users perspective
            var loggerTypeDefinition = HasCompilerGeneratedAttribute && _typeDefinition.IsNested
                                                ? _typeDefinition.DeclaringType :  _typeDefinition;

            staticConstructor.Body.InsertAtTheBeginning(new[]
            {
                Instruction.Create(OpCodes.Ldtoken, loggerTypeDefinition.GetGenericInstantiationIfGeneric()),
                Instruction.Create(OpCodes.Call, getTypeFromHandleMethod),
                Instruction.Create(OpCodes.Call, getLoggerMethod),
                Instruction.Create(OpCodes.Stsfld, loggerFieldRef)
            });

            return loggerFieldRef;
        }