这是WP7和WP8之间代码共享的一个很好的问题。
最简单的方法你要做的就是在运行时读取AppManfiest.xml文件,获取EntryType并使用它获取入口点Assembly实例。下面是一个示例AppManfiest.xml怎么看起来像曾经的MSBuild做它的魔力就可以了:
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" EntryPointAssembly="myAssembly" EntryPointType="myNamespace.App" RuntimeVersion="4.7.50308.0">
<Deployment.Parts>
<AssemblyPart x:Name="myAssembly" Source="myAssembly.dll" />
</Deployment.Parts>
</Deployment>
而且这里是你将如何读取文件,获得的属性,然后获取入口点类型,最后的入口点组件:
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var appManfiest = XElement.Load("AppManifest.xaml");
var entryAssemblyName = appManfiest.Attribute("EntryPointAssembly").Value;
var entryTypeName = appManfiest.Attribute("EntryPointType").Value;
Type entryType = Type.GetType(entryTypeName + "," + entryAssemblyName);
Assembly entryAssembly = entryType.Assembly;
}
这是一个简单的解决方案,它的工作原理。但是,这不是最干净的架构解决方案。我实现这个解决方案的方式是在共享库中声明一个接口,WP7和WP8都实现该接口,并使用IoC容器注册它们的实现。
例如,假设您需要在平台版本特定的共享库中“DoSomething”。首先你会创建一个IDoSomething接口。我们还假设你有一个IoC支持。
public interface IDoSomething
{
}
public static class IoC
{
public static void Register<T>(T t)
{
// use some IoC container
}
public static T Get<T>()
{
// use some IoC container
}
}
在WP7应用程序中,您将实现WP7的共享接口并在WP7启动后注册它。
public App()
{
MainPage.IoC.Register(new MainPage.DoSomethingWP7());
}
private class DoSomethingWP7 : IDoSomething
{
}
您也将在WP8应用程序中为WP8做同样的事情。然后在共享库中,您可以请求相关接口,而不管其平台版本的具体实现如何:
IDoSomething sharedInterface = IoC.Get<IDoSomething>();