T4 Templating with 3rd party assemblies

4k views Asked by At

I have the need to do JSON schema generation within a T4 template, and found Newtonsoft's new Schema class more than adequate for the purpose at hand (within a console application, tested), however, I cannot seem to make it play ball with the rest, as the instance to Newtonsoft always returns null.

T4 declaration:

<#@ template debug="true" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="Newtonsoft.Json.dll" #>
<#@ assembly name="Newtonsoft.Json.Schema.dll" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>

The assembly references point to the DLL files, and I have folder look ups set in the project settings for the project, screen shot below:

enter image description here

Trying to do something like the below, fails, because Newtonsoft cannot be found:

var schema = Newtonsoft.Json.Schema.JSchema.Parse(jsoncontent);

Error thrown is: Metadata file 'Newtonsoft.Json.Schema.dll" could not be found.

2

There are 2 answers

4
Matt Ward On BEST ANSWER

T4 templates do not use the reference path defined in the project. T4 does support some variables inside Visual Studio:

<#@ assembly name="$(SolutionDir)\MyProject\bin\Debug\SomeLibrary.Dll" #>

There is an existing StackOverflow question about this.

If you are referencing the .dll and it is being copied into the output directory you should be able to use $(TargetDir) in the path so you do not need to include the NuGet package version number which will change when you update the NuGet package.

0
JadedEric On

Found the solution to this was not as specific as the original error stated.

My Newtonsoft.Json version is version 7.0.1 but the compiled version of Newtonsoft.Json.Schema was against version 6.0.8, which caused an internal "version difference" error, but never got raised to the top of the stack, and T4 just notified that the metadata could not be found (theoretically correct) but not very specific.

I grabbed a copy of Newtonsoft.Json.Schema from GitHub, and compiled that against version 7, from NuGet and the error went away.