简体   繁体   English

无法将System.Net.Sockets添加到Xamarin PCL项目中,可以使用“诱饵和切换”高级PCL方法来完成吗?

[英]Can't add System.Net.Sockets to a Xamarin PCL project can this be done using “Bait and switch” advanced PCL approach?

I can't add System.Net.Sockets to a Xamarin PCL project can this be done using "Bait and switch" AKA advanced PCL approach? 我无法将System.Net.Sockets添加到Xamarin PCL项目中,可以使用“诱饵和开关” AKA高级PCL方法来完成此操作吗?

System.Net.Sockets is available for Xamarin.iOS and Xamarin.Android projects System.Net.Sockets可用于Xamarin.iOS和Xamarin.Android项目

Explanation of Bait and switch 诱饵和开关的说明

Yes, this is possible. 是的,这是可能的。 The approach we use is to make separate iOS and Android Class libraries that will hold non-UI type code that is not accessible from PCL, and have that code implement interfaces that are accessible from the shared PCL layer. 我们使用的方法是制作单独的iOS和Android类库,这些库将保存从PCL无法访问的非UI类型的代码,并使该代码实现可从共享PCL层访问的接口。

For example: 例如:

Create ISocketHandler in Shared PCL project, and it has OpenConnection method. 在Shared PCL项目中创建ISocketHandler,它具有OpenConnection方法。

Create an iOS.Framework class library, and in it create an iOSSocketHandler class that implements ISocketHandler and has platform specific code on using sockets in Xamarin iOS. 创建一个iOS.Framework类库,并在其中创建一个iOSSocketHandler类,该类实现ISocketHandler并具有有关在Xamarin iOS中使用套接字的平台特定代码。 Do the same for Android. 对Android执行相同的操作。

Then you need dependency injection so that whenever your shared code asks for ISocketHandler, they get the appropriate implementation. 然后,您需要进行依赖项注入,以便每当您的共享代码要求ISocketHandler时,它们都将获得适当的实现。 We use Unity, and in our Main.cs we will register like so: 我们使用Unity,并在Main.cs中像这样注册:

IocContainer.GetContainer().RegisterType<ISocketHandler, iOSSocketHandler>();

Then in your shared code you can request the implementation like so: 然后,您可以在共享代码中请求实现,如下所示:

IocContainer.GetContainer().Resolve<ISocketHandler>();

There are other strategies that can accomplish what you want, but this is what we use in most scenarios. 还有其他策略可以满足您的需求,但这是我们在大多数情况下使用的策略。

Also, before trying to do this yourself, you may want to check this out https://github.com/rdavisau/sockets-for-pcl 另外,在尝试自己执行此操作之前,您可能需要检查一下https://github.com/rdavisau/sockets-for-pcl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM