public CodeCompileUnit GetCodeCompileUnit(string className, string template, ISet <string> namespaceImports, Type templateType, Type modelType)
        {
            if (string.IsNullOrEmpty(className))
            {
                throw new ArgumentException("Class name is required.");
            }

            if (string.IsNullOrEmpty(template))
            {
                throw new ArgumentException("Template is required.");
            }

            namespaceImports = namespaceImports ?? new HashSet <string>();
            templateType     = templateType ?? ((modelType == null) ? typeof(TemplateBase) : typeof(TemplateBase <>));

            // Create the RazorEngineHost
            var host = CreateHost(templateType, modelType, className);

            // Add any required namespace imports
            foreach (string ns in GetNamespaces(templateType, namespaceImports))
            {
                host.NamespaceImports.Add(ns);
            }

            // Gets the generator result.
            GeneratorResults result = GetGeneratorResult(host, template);

            // Add the dynamic model attribute if the type is an anonymous type.
            var type = result.GeneratedCode.Namespaces[0].Types[0];

            if (modelType != null && CompilerServicesUtility.IsAnonymousType(modelType))
            {
                type.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(HasDynamicModelAttribute))));
            }

            // Generate any constructors required by the base template type.
            GenerateConstructors(CompilerServicesUtility.GetConstructors(templateType), type);

            // Despatch any inspectors
            Inspect(result.GeneratedCode);

            return(result.GeneratedCode);
        }
示例#2
0
 /// <summary>
 /// Initialises a new instance of <see cref="TypeContext"/>.
 /// </summary>
 internal TypeContext()
 {
     ClassName  = CompilerServicesUtility.GenerateClassName();
     Namespaces = new HashSet <string>();
 }