10

I need to be able to use a class inside a T4 template, both of which reside in my solution. I have a class named Container in Container.cs. In my text template I want to be able to Access Container class. Any ideas on how can i do this. Basically something like this:

<#@ template language="C#" #>

<# var container = new Container() #>

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
user1396149
  • 115
  • 1
  • 7

1 Answers1

16

In general, if you need to actually use the Container class's functionality in your template, you'll want to load the assembly that your project is building. This does introduce a circular dependency, as you need a built version of your assembly in order to regenerate code that is going to be included in that assembly, so be aware of that.

If you're using VS2010 or above, you'll be able to use something like:

<#@ assembly name="$(TargetPath)" #>
<#@ import namespace="Your.Namespace" #>

and then use your Container class.

If you have VS2010SP1 or above, this will cause you no probelms with locking that assembly in memory, but if you're earlier than that, then you'll have to restart Visual Studio after each generation before you can rebuild your project.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
GarethJ
  • 6,496
  • 32
  • 42
  • 2
    Another option in T4 templates is to [File.ReadAllBytes()](http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes.aspx) and then [Assembly.Load()](http://msdn.microsoft.com/en-us/library/h538bck7.aspx) the byte array into memory. This would require fulling qualified classes `new namespaces.class()` but means you don't have to restart Visual Studio each time. – Erik Philips Jun 19 '12 at 00:21
  • Answer works with VS2017, 4.8 framework. Excellent! – petrosmm Dec 26 '19 at 21:16