Using Model from another .csproj throws exception of type 'SharpDocx.SharpDocxCompilationException'
Hi @egonl ,
I am using SharpDocx v2.2.0 inside a .NET 6 console app and I am getting SharpDocxCompilationException when using a ViewModel containing a collection of objects residing in a separate project:
The CurrentViewModel is defined in Assembly A. The Item class is defined in Assembly B. Assembly A has a reference to Assembly B.
public class CurrentViewModel
{
public CurrentViewModel()
{
Sensors = new List<Sensor>();
}
public List<Item> Items { get; set; }
}
When I run this code:
var currentViewModel = new CurrentViewModel();
var document = DocumentFactory.Create("initial_document.docx", currentViewModel );
document.Generate("final_document.docx");
I get this exception:
The type 'your_type' is defined in an assembly that is not referenced. You must add a reference to assembly 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
I tried adding these lines inside the Word document:
< %@ Assembly Name="B" % >
<%@ Import Namespace="B"%>
with no luck.
I had a similar problem (you might have solved it but it might be helpful for someone else), I found I had to create an object that inherited from DocumentBase. The Inheritance example in the documentation for SharpDocx was helpful.
Creating the document using my custom class.
var document DocumentFactory.Create<CustomDobument>(path, modelObject);
The class looked something like this. By specifying the assemblies and using references I did not have to attempt to import anything from the word document itself. I found that it could find the assembly in a console app but not in an asp.net web app so handling it myself solved the problem for me.
public abstract class CustomDocument : DocumentBase
{
public static new static List<string> GetReferencedAssemblies()
{
return new List<string>
{
typeof(CustomObject).Assembly.Location
};
}
public static new static List<string> GetUsingDirectives()
{
return new List<string>
{
"using CustomAssembly.Namespace.Path"
};
}
}