DependencyService.Get<InterfaceImplemetation>() returns 空

DependencyService.Get<InterfaceImplemetation>() returns null

我已经实施了一个 DependencyService 来更改特定页面的设备方向。

ScreenRotation.cs

[assembly: Dependency(typeof(WhaleEstimate.Droid.ScreenRotation))]
        namespace WhaleEstimate.Droid
        {
            class ScreenRotation : IScreenRotation
            {
                public void DisableScreenRotation()
                {
                    Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
                }

                public void EnableScreenRotation()
                {
                    Platform.CurrentActivity.RequestedOrientation = Android.Content.PM.ScreenOrientation.FullSensor;
                }
            }
        }

PCL中的代码:

private IScreenRotation screenRotationService;
screenRotationService = DependencyService.Get<IScreenRotation>();
if (screenRotationService != null)
{
     screenRotationService.EnableScreenRotation();
}

执行时,到达if子句中的Code-Snippet。然后抛出 NullReferenceException。我完全不知道,为什么它会到达 if 子句中的代码片段以及为什么对象为空。

编辑

异常信息:

首先。您是否在 Initialization 中注册了依赖服务?。在 app.xaml.cs

DependencyService.Register<IService, Service>();

此外,尝试使 class public

您好,我使用了 CurrentActivity 插件,它对我有用。 我想你忘了在你的 Android 项目 MainActivity.cs 文件

中初始化插件

MainActivity.cs

protected override void OnCreate(Bundle savedInstanceState)
        {

            base.OnCreate(savedInstanceState);
            Xamarin.Forms.Forms.SetFlags("Expander_Experimental");
            CrossCurrentActivity.Current.Init(this, savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }

Android

ScreenRotation.cs

using Plugin.CurrentActivity;
using Xamarin.Forms;
[assembly: Dependency(typeof(TestMobileApp.Droid.ScreenRotation))]
namespace TestMobileApp.Droid
{
    public class ScreenRotation : IScreenRotation
    {
        public void DisableScreenRotation()
        {
            CrossCurrentActivity.Current.Activity.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
        }

        public void EnableScreenRotation()
        {
            CrossCurrentActivity.Current.Activity.RequestedOrientation = Android.Content.PM.ScreenOrientation.FullSensor;

        }
    }
}

您收到 NullReferenceException 可能是因为 Android.Content 为空,因此给您例外,请尝试将 ScreenRotation 更改为此,以便您获得 Activity 上下文:

public class ScreenRotation : IScreenRotation
{
    public void DisableScreenRotation()
    {
        var activity = (Activity)Forms.Context;
        activity.RequestedOrientation = ScreenOrientation.Portrait; 
    }

    public void EnableScreenRotation()
    {
         var activity = (Activity)Forms.Context;
         activity.RequestedOrientation = ScreenOrientation.FullSensor; 
    }
}