Exemple #1
0
        private Type MakeTypeImplementing(Type interfaceType, bool isFuzzy)
        {
            if (!interfaceType.IsInterface)
            {
                throw new InvalidOperationException(
                          "MakeTypeImplementing<T> requires an interface for the type parameter");
            }
            var identifier = Guid.NewGuid().ToString("N");
            var moduleName = string.Join("_", identifier, "_Gen_", interfaceType.Name);
            var modBuilder = DynamicAssemblyBuilder.DefineDynamicModule(moduleName);

            var generatedTypeName = interfaceType.Name + "_Duck_" + identifier;
            var typeBuilder       = modBuilder.DefineType(generatedTypeName, TypeAttributes.Public);

            var attribConstructor = typeof(IsADuckAttribute).GetConstructor(new Type[0]);
            // we have full control over the constructor; testing for null is a waste of time.
            // ReSharper disable once AssignNullToNotNullAttribute
            var attribBuilder = new CustomAttributeBuilder(attribConstructor, new object[0]);

            typeBuilder.SetCustomAttribute(attribBuilder);
            CopyCustomAttributes(interfaceType, typeBuilder);

            typeBuilder.AddInterfaceImplementation(interfaceType);

            var shimField         = AddShimField(typeBuilder);
            var allInterfaceTypes = interfaceType.GetAllImplementedInterfaces();

            AddAllPropertiesAsShimmable(typeBuilder, allInterfaceTypes, shimField);
            AddAllMethodsAsShimmable(typeBuilder, allInterfaceTypes, shimField);

            AddDefaultConstructor(typeBuilder, shimField, interfaceType, isFuzzy);
            AddObjectWrappingConstructors(typeBuilder, shimField, interfaceType, isFuzzy);
            AddDictionaryWrappingConstructors(typeBuilder, shimField, interfaceType);

#if NETSTANDARD
            return(typeBuilder.CreateTypeInfo());
#else
            return(typeBuilder.CreateType());
#endif
        }
Exemple #2
0
        private static ModuleBuilder CreateModuleBuilder()
        {
            var moduleName = "__PeanutButter_DuckTyped_Gen__";

            return(DynamicAssemblyBuilder.DefineDynamicModule(moduleName));
        }