예제 #1
0
        public CSharpSourceTree Execute(RazorCodeDocument document, CSharpSourceTree sourceTree)
        {
            var modelType = GetDeclaredModelType(sourceTree);
            var classInfo = document.GetClassName();

            if (modelType == null)
            {
                // Insert a model directive into the system so sub-systems can rely on the model being the class.
                var modelTokens = new List <RazorDirectiveToken>()
                {
                    new RazorDirectiveToken
                    {
                        Descriptor = new RazorDirectiveTokenDescriptor {
                            Type = RazorDirectiveTokenType.Type
                        },
                        Value = classInfo.Class,
                    }
                };
                var modelDirective = new RazorSingleLineDirective()
                {
                    Name   = "model",
                    Tokens = modelTokens,
                };
                sourceTree.Children.Insert(0, modelDirective);
                modelType = classInfo.Class;
            }

            // Inject properties needed to execute Razor pages.
            var classDeclaration = FindClassDeclaration(sourceTree);

            var viewDataType = $"global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<{modelType}>";

            classDeclaration.Children.Insert(0, new RenderStatement()
            {
                Code = $"public {modelType} Model => ViewData.Model;",
            });

            var viewDataProperty = new RenderStatement
            {
                Code = $"public new {viewDataType} ViewData => ({viewDataType})base.ViewData;"
            };

            classDeclaration.Children.Insert(0, viewDataProperty);

            var injectHtmlHelper = CreateInjectDirective($"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<{modelType}>", "Html");

            sourceTree.Children.Insert(0, injectHtmlHelper);

            var injectLogger = CreateInjectDirective($"Microsoft.Extensions.Logging.ILogger<{classInfo.Class}>", "Logger");

            sourceTree.Children.Insert(0, injectLogger);

            return(sourceTree);
        }