これは、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>();