Exemplo n.º 1
0
    public void Execute()
    {
        foreach (var type in ModuleDefinition.Types) {
         var defaultConstructorAttribute = type.FindAndActivateCustomAttributeOrNull<DefaultConstructorAttribute>();
         var otherConstructorAttributes = new AbstractConstructorAttributeBase[] {
            type.FindAndActivateCustomAttributeOrNull<RequiredFieldsConstructorAttribute>(),
            type.FindAndActivateCustomAttributeOrNull<UninitializedFieldsConstructorAttribute>(),
            type.FindAndActivateCustomAttributeOrNull<AllFieldsConstructorAttribute>()
         }.Where(x => x != null).ToArray();

         if (defaultConstructorAttribute == null && otherConstructorAttributes.Length == 0) continue;

         var defaultConstructor = FindOrCreateAndAddDefaultConstructor(type).Resolve();
         defaultConstructor.IsPublic = defaultConstructorAttribute != null;

         foreach (var constructorAttribute in otherConstructorAttributes) {
            var fieldsToInitialize = FindMatchingFields(type, defaultConstructor, constructorAttribute);
            var injectionConstructor = CreateInjectionConstructor(type, defaultConstructor, fieldsToInitialize);
            MethodDefinition similarConstructor;
            if (!TryFindSimilarConstructors(type.Methods, injectionConstructor, out similarConstructor)) {
               type.Methods.Add(injectionConstructor);
            } else {
               similarConstructor.IsPublic = true;
            }
         }
          }
    }
Exemplo n.º 2
0
 private IList<FieldDefinition> FindMatchingFields(TypeDefinition type, MethodDefinition defaultConstructor, AbstractConstructorAttributeBase constructorAttribute)
 {
     var matches = new List<FieldDefinition>();
       var initializedFields = EnumerateInitializedFields(defaultConstructor);
       foreach (var field in type.Fields) {
      if (field.IsStatic) {
         continue;
      }
      var fieldInfo = new FieldInfo {
         IsInitOnly = field.IsInitOnly,
         HasNonDefaultFieldInitializer = initializedFields.Contains(field)
      };
      if (constructorAttribute.Condition(fieldInfo)) {
         matches.Add(field);
      }
       }
       return matches;
 }