Saturday, September 10, 2011
Referencing Silverlight assemblies from non-SL projects
One of the best things about Silverlight is that represents a set of portable functionality that you can expect to run almost anywhere. Its similarity – although reduced – with WPF results in an amazing way to develop rich UIs and logic in Browser-side apps. And then results normal to want to reuse Silverlight code from our own .NET applications.
Reusing code from Silverlight assemblies is possible; the referencing process works well because Silverlight is a subset of .NET Framework, so that “by logic” should just work. Of course this is not all happiness, there are lot of limitations, but it will work as long as you keep yourself into the borders of certain assemblies like Mscorlib , System ,System.Core ,System.ComponentModel.Composition and Microsoft.VisualBasic , playing with others might give you mixed results.
Now the trick.
You SHOULD NOT add the reference to the Silverlight PROJECT.
You MUST add the reference to the Silverlight ASSEMBLY.
So let’s assume you have a scenario with 2 projects, SilverlightCommonTools.dll and WPFMain.exe, targeting Silverlight and WPF respectively.
1) Compile your Silverlight library project.
2) Add a reference to your WPF project, locate the compiled Silverlight dll on disk.
3) Code, compile and run!
NOTE: I have selected WPF as an example, but you can reuse your Silverlight code from any .NET code.
The Weird Errors
If you add a reference to the project in Visual Studio, instead of doing what I just said above, you might experience some very weird error messages. Specially some “Could not load assembly ‘some.asembly.dll’”. The “missing” assembly changes depending on your scenario. I got this one from a console app:
Could not load file or assembly 'System.Xml.Linq, Version=126.96.36.199, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified
And got this one from an ASP.NET:
Could not load file or assembly 'System.Windows, Version=188.8.131.52, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified
It is also important to notice that at least for me, project always compiled fine, the problem was at runtime. But don’t worry, as long as you remember to reference the DLL file directly instead of the project, you will be ok.