Sharing C# code between Windows and Silverlight class libraries

你说的曾经没有我的故事 提交于 2019-11-27 22:56:09

You cannot set a reference from a Silverlight assembly to a regular .NET assembly but you can do so the other way round.

So create a shared Silverlight assembly and add your code to that assembly. Now you can set a reference fro both your regular .NET and you other Silverlight assembly to the shared Silverlight assembly.

The restriction is that you can only put code in there that would work on both the .NET and Silverlight CLR but that is no different from sharing code.

Since this question has been answered, there is a new solution from Microsoft, Portable Class Libraries. Here is the blog post where they announced it.

I'm just about to start playing round with them for sharing code between silverlight and some server side code I'm writing, so can't add too much past the links at the moment.

Silverlight runtime is different from the normal .NET runtime. So you need to do tricks at the project level to share code between multiple platforms.

Here's how I've done this for Autofac IoC container.

With this approach you do not have to create different projects for each platform being targeted.

PS: there is also a Project Linker tool from the Composite WPF that allows to link Silverlight and WPF projects (creates multiple projects). But it does look messy.

there is a similar problem with XNA projects. Since you can target several different platforms, you're required to have different projects. The reason for this is because the base class libraries that the project references are platform specific, so you can't have just one project.

If you're curious, you can get a bit of insight from this blog:

To recompile the source for another platform, you need another project. The reason for this is because the projects need to reference different assemblies for both the XNA Framework and the underlying .NET Framework (Xbox 360 and Zune use the .NET Compact Framework), and C# projects don't provide support for referencing different assemblies for different platforms.

I had some dependency issues when referencing to a Silveright class library in .Net.

An alternative way when using Visual Studio 2010 and WCF RIA 1.0:

  • Create a normal .Net library assembly.
  • Create a Silverlight class library. In the configuration of the assembly specifiy the first .NET library as the "WCF RIA Service link"
  • Put your code in the .NET library as "ClassName.shared.cs" files.
  • WCF RIA will handle copying the file to the Silverlight assembly.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!