Search code examples
c#meft4envdte

Accessing VS' ITextTemplatingEngineHost in Preprocessed T4 Template in a VS Extension


I've tried to follow this example:

http://msdn.microsoft.com/en-us/library/gg586947.aspx

And trying to work out how to refactor the following existing code so we can use VS' ITextTemplatingEngineHost.

        template.DatabaseObjectNameWithSchema = databaseObjectName;
        template.Database = database;
        template.Namespace = templateNamespace;
        template.Dialect = dialect;

        template.Host = ???

        return template.TransformText();

I can get the templating service and the session host:

        ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating)) as ITextTemplating;
        ITextTemplatingSessionHost sessionHost = t4 as ITextTemplatingSessionHost;

However, I can't for the life of me work out how to get the Engine host...


Solution

  • It sounds like you are trying to get this interface: ITextTemplatingEngineHost. If so you can try this code:

    STextTemplating vsHost = (STextTemplating)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(STextTemplating));
    var vsHostEngine = vsHost as ITextTemplatingEngineHost;
    

    To fully understand how T4 templating works you can use a tool like reflector and view the source. Search for a file on your machine named Microsoft.VisualStudio.TextTemplating.VSHost.11.0.dll or something similar, not sure what version of visual studio you are using. If you open that file up in reflector and study it you should be able to find any answer you need.