This project is read-only.

Error with dynamically loaded assembly

Apr 6, 2012 at 3:44 PM
Edited Apr 6, 2012 at 3:48 PM

Error text:

System.Diagnostics.Contracts.__ContractsRuntime+ContractException: Precondition failed: templateType != null
at System.Diagnostics.Contracts.__ContractsRuntime.TriggerFailure(ContractFailureKind kind, String message, String userMessage, String conditionText, Exception inner)
at System.Diagnostics.Contracts.__ContractsRuntime.ReportFailure(ContractFailureKind kind, String message, String conditionText, Exception inner)
at System.Diagnostics.Contracts.__ContractsRuntime.Requires(Boolean condition, String message, String conditionText)
at RazorEngine.Templating.InstanceContext..ctor(TypeLoader loader, Type templateType)
at RazorEngine.Templating.TemplateService.CreateInstanceContext(Type templateType)
at RazorEngine.Templating.TemplateService.CreateTemplate(Type templateType)
at RazorEngine.Templating.TemplateService.CreateTemplate(Type templateType, T model)
at RazorEngine.Templating.TemplateService.CreateTemplate(String razorTemplate, T model)
at RazorEngine.Templating.TemplateService.Parse(String razorTemplate, T model)
at System.Dynamic.UpdateDelegates.UpdateAndExecute3<T0,T1,T2,TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2)
at TestConsoleApp.TemplateService.Parse(String templateFileName, Object model) in TemplateService.cs: line 28
at System.Dynamic.UpdateDelegates.UpdateAndExecute3<T0,T1,T2,TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2)
at TestConsoleApp.Tests.UnitTest1.TestMethod2() in UnitTest1.cs: line 56


The unit test to generate the error:

public void TestMethod2()
var template = "<h1>This is ID @Model.Id</h1><p>Items count: @Model.Items.Count()</p><p>Regards</p>";
var model = new Model { Id = 12, Items = new List<string> { "", "", "" } };
var expectedResult = "<h1>This is ID 12</h1><p>Items count: 3</p><p>Regards</p>";

var assembly = Assembly.LoadFrom(@"..\..\..\TestConsoleApp\bin\Debug\TestConsoleApp.dll");

dynamic builder = assembly.CreateInstance("TestConsoleApp.TemplateService", true, BindingFlags.Instance | BindingFlags.Public, null, null, null, null);

var result = builder.Parse(template, model);

Assert.AreEqual(expectedResult, result);


The model for template:

public class Model
        public int Id { get; set; }
        public List<string> Items { get; set; }


Template service in TestConsoleApp:

public class TemplateService
    public string Parse(string template, dynamic model)
        return Razor.Parse(template, model);


Any comments are welcome!