Search code examples
androidxamarinrealm.net-standard-2.0

System.Runtime.CompilerServices.Unsafe while running .Net Standard project in Xamarin


i am creating an app in xamarin using .Net Standard so far i have installed following Nuget packages in my solution

PCL/.Net Standard packages

enter image description here

Android packages

enter image description here

Min SDK level is Android 5.1 and max is Android Oreo 8.1.

When i run the app in visual studio VS2017 it runs for few seconds and closed down abruptly and throwing following error

04-06 02:45:11.182 6262-6262/com.org.sam A/monodroid-assembly: Could not load assembly 'System.Runtime.CompilerServices.Unsafe' during startup registration.
04-06 02:45:11.182 6262-6262/com.org.sam A/monodroid-assembly: This might be due to an invalid debug installation.
04-06 02:45:11.182 6262-6262/com.org.sam A/monodroid-assembly: A common cause is to 'adb install' the app directly instead of doing from the IDE. 
  1. i tried cleaning the solution many times and removing bin and obj folders too but i am getting the same error.

  2. I have not written any code anywhere as i am just migrating the project so this project is blank.

I personally think Realm has the System.Runtime.CompilerServices reference and due to that its creating issue. here is the screenshot of realm installing from nuget

enter image description here


Solution

  • I also had this error, but it was when using Entity Framework from a .net standard library. This took quite a while to sort out! Hopefully this will work for you.

    In the android project add the following as an XmlFile eg(UnsafeCompilerWorkaround.xml):

    <Project>
      <Target Name="ReplaceRefAssemblies" AfterTargets="_ResolveAssemblies">
        <ItemGroup>
          <ResolvedAssembliesFixedWindows Include="@(ResolvedAssemblies->Replace('\ref\','\lib\'))" />
          <ResolvedAssembliesFixedUnix Include="@(ResolvedAssemblies->Replace('/ref/','/lib/'))" />
          <ResolvedAssembliesFixed Include="@(ResolvedAssembliesFixedWindows)" Condition="@(ResolvedAssembliesFixedWindows) != @(ResolvedAssemblies)" />
          <ResolvedAssembliesFixed Include="@(ResolvedAssembliesFixedUnix)" Condition="@(ResolvedAssembliesFixedUnix) != @(ResolvedAssemblies)" />
          <ResolvedAssemblies Remove="@(ResolvedAssemblies)" />
          <ResolvedAssemblies Include="@(ResolvedAssembliesFixed)" />
        </ItemGroup>
      </Target>
    </Project>
    

    Edit the android.csproj file and add the following import

      <Import Project="UnsafeCompilerWorkaround.xml"></Import>
    

    Then clean and rebuild the solution.