Forms.context已过时。Context自版本2.5起已过时,请改用本地上下文

时间:2018-06-21 06:31:55

标签: xamarin.forms azure-active-directory

我遇到了这个问题: Forms.context已过时。Context从2.5版开始已过时,请改用本地上下文。

我正在尝试使用带有以下代码的Azure Active Directory登录。 请帮忙。

using Xamarin.Forms;
using myMobile.Service;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading.Tasks;

[assembly: Dependency(typeof(myMobile.Droid.Authenticator))]
namespace myMobile.Droid
{
    class Authenticator: IAuthenticator 
    {
        public async Task<AuthenticationResult> Authenticate(string tenantUrl, string graphResourceUri, string ApplicationID, string returnUri)
        {
            try
            {
                var authContext = new AuthenticationContext(tenantUrl);
                if (authContext.TokenCache.ReadItems().Any())
                    authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().FirstOrDefault().Authority);

  var authResult = await authContext.AcquireTokenAsync(graphResourceUri, ApplicationID, new Uri(returnUri), new PlatformParameters((Activity)Forms.Context));

                return authResult;
            }
            catch (Exception)       
            {
                return null;
            }
        }
    }
}


// err encountered on this line :(Activity)Forms.Context)

 Forms.context is obsolete.Context is obsolete as of version2.5,please use a local context instead.

var authResult = await authContext.AcquireTokenAsync(graphResourceUri, ApplicationID, new Uri(returnUri), new PlatformParameters((Activity)Forms.Context));

// ---更新:

 //-------- Login Page:

private async void Login()
{           
     try
     {
       var data = await DependencyService.Get<IAuthenticator>()
                  .Authenticate(AzureSettings.tenanturl, AzureSettings.GraphResourceUri, AzureSettings.ApplicationID, AzureSettings.ReturnUri);

  AzureSettings.AuthenticationResult = data;

                //NavigateTopage(data);

            }
            catch (Exception)
            { }
        }
   }

//--------- in Shared Project :

//-- interface: IAuthenticator


using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading.Tasks;

namespace myMobile.Service
{
    public interface IAuthenticator
    {
        Task<AuthenticationResult> Authenticate(string tenantUrl, string graphResourceUri, string ApplicationID, string returnUri);
    }
}



//-------- in Android Project: add

1) Class : Authenticator.cs

using Android.App;
using Android.Content;
using Xamarin.Forms;
using myMobile.Service;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading.Tasks;

[assembly: Dependency(typeof(myMobile.Droid.Authenticator))]
namespace myMobile.Droid
{
    class Authenticator: IAuthenticator 
    {
        private readonly Context _context;

        public static void Init(Context context)
        {
            _context = context;  //--error 
        }


        public async Task<AuthenticationResult> Authenticate(string tenantUrl, string graphResourceUri, string ApplicationID, string returnUri)
        {
            try
            {
                var authContext = new AuthenticationContext(tenantUrl);
                if (authContext.TokenCache.ReadItems().Any())
                    authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().FirstOrDefault().Authority);

var authResult = await authContext.AcquireTokenAsync(graphResourceUri, ApplicationID, new Uri(returnUri), new PlatformParameters((Activity) _context));

                return authResult;
            }
            catch (Exception)       
            {
                return null;
            }
        }
    }
}

error : 

An Object reference is required for non-static field,method or property.Authenticator._context



//------- Class: MainActivity



namespace myMobile.Droid
{
    [Activity(Label = "myMobile", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

               DependencyService.Get<IAuthenticator>().Init(this);  //<-- Error

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());
        }
    }
}

Error Message:

IUAthenticator does not contain a definition for Init and no extension method accepting
a first argument of  type IAuthenticator

1 个答案:

答案 0 :(得分:1)

您现在必须实现一个自定义构造函数,该构造函数将Context放在本地变量中,并在实例new PlatformParameters((Activity)Forms.Context)中使用它代替它。

对于自定义渲染器,可以使用下面的解决方案。这样做:

public MyControlRenderer : ControlRenderer
{
    private readonly Context _context;

    public MyControlRenderer(Context context) : base(context)
    {
        _context = context;
    }
}

对于像您这样的依赖服务,您将必须找到一种提供Context的方法。由于Xamarin.Forms使用单个活动,因此您可以摆脱某种init方法。

将此添加到您的代码中:

public class MyService : IMyService
{
    private static Context _context;

    public static void Init(Context context)
    {
        _context = context;
    }
}

现在从您的Init中呼叫MainActivity,之后您应该会很好。也是这样:DependencyService.Get<IMyService>().Init(this);

对于其他人从事多种活动的其他活动,请参考此处的文档:https://www.davidbritch.com/2017/11/xamarinforms-25-and-local-context-on.html