【问题标题】:Xamarin.Forms Dependency Service UWP: methodNotFoundExceptionXamarin.Forms 依赖服务 UWP:methodNotFoundException
【发布时间】:2017-09-09 06:56:47
【问题描述】:

我有一个针对 Android、iOS、UWP 和 Windows10 的 Xamarin Forms 便携式项目。我想从 Portable 项目中调用特定平台代码(UWP、Android、iOS、win10)。谷歌搜索似乎可以使用Dependency Service 来完成。 我在调用 UWP 代码时遇到了一些问题。按照教程,我在 Portable 项目中创建了一个界面,如下所示:

namespace PushClient
{
    public interface IWebSocket
    {

        void test();

    }
} 

然后在 UWP 项目中我创建了一个实现接口的类:

[assembly: Xamarin.Forms.Dependency(typeof(PushClient.UWP.WebSocketUWP))]
namespace PushClient.UWP
{
    public class WebSocketUWP : IWebSocket
    {
        public WebSocketUWP() {}
        public void test() { System.Diagnostics.Debug.WriteLine("UWP TEST"); }

    }
}

然后在 UWP 项目的 App.xaml.cs 文件中,我注册了如下依赖:

        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {

#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif



            List<Assembly> assembliesToInclude = new List<Assembly>();


            assembliesToInclude.Add(typeof(WebSocketUWP).GetTypeInfo().Assembly);

            Xamarin.Forms.Forms.Init(e, assembliesToInclude);


            Xamarin.Forms.DependencyService.Register<IWebSocket>();

// [...]

}

当我尝试从 Portable 项目中的共享代码中调用 UWP 测试方法时,像这样

DependencyService.Get<IWebSocket>().test();

一个 methodNotFoundException 被抛出。我做错了什么?

【问题讨论】:

    标签: c# service dependency-injection xamarin.forms portable-class-library


    【解决方案1】:

    问题之后有点长,但答案可能仍然对某人有任何兴趣.. 在 UWP 中,您必须进行 2 次注册,一种像其他平台一样具有程序集属性,另一种是 app.xaml.cs 中的“手动”。

    在上面的代码中,错误的部分是在app.xaml.cs中为接口完成了注册……这不是必须注册的接口,而是UWP的实现类。

    也许这会拯救某人的一天,有一天,地球上的某个地方,或其他地方,谁知道......

    【讨论】:

    • 谢谢。我一直在努力解决这个问题,而您的回答挽救了我的一天。
    猜你喜欢
    • 2019-05-11
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2015-09-03
    • 2021-07-05
    相关资源
    最近更新 更多