我正在使用Freshmvvm作为我的Xamarin表单项目。我正在使用一个相机,并希望使用平台特有的功能。因此,我想知道如何使用IOC控件来使用特定于平台的特性。
Freshmvvm.FreshIOC.Container.Register<ICamera,Camera>();如果我从App调用这个代码,我是否需要在iOS和安卓项目中都有摄像头类,如果是,那么如何让应用类知道我们想要实现一个特定平台的摄像机类?或者是否有更好的方法来使用IOC控件并在我们想要使用它时将接口注入页面模型(视图模型)的构造器中?
发布于 2016-09-14 20:13:59
我想你要找的是受扶养人处。这使您能够访问本机功能。
这样,您就必须在共享代码中创建一个接口,例如ICamera。
public interface ICamera
{
void TakePicture();
}现在,您可以在平台特定的项目中实现此接口。
例如,在iOS上,您可以这样实现它:
公共类CameraImplementation : ICamera { public void TakePicture() { // iOS代码这里}
这里的关键是你如何注册这个。您可以通过在平台特定实现的命名空间上添加这样的标记来完成这一任务,如下所示:
[assembly: Xamarin.Forms.Dependency (typeof (CameraImplementation))]
namespace yourapp
{
// CameraImplementation class here
}Android也是如此。如果您保持相同的命名,您甚至可以复制和粘贴这个标签。
发布于 2019-03-19 17:42:52
免责声明:我对IOC、DI和FreshMvvm非常陌生。刚刚得到这工作为我自己,并希望分享,以帮助其他一些人,以防止他们偶然发现这个论坛,像我一样。
Xamarin表单提供的DependencyService非常棒,但仍然有限(例如不能实现构造函数注入)。在使用DependencyService的同时实现单元测试也会变得有点麻烦。这里是一个教程,如果您坚持使用DependencyService,但也希望对代码进行单元测试,它将带您完成一些步骤。它是一个服务定位器,它比依赖注入更难测试(在我看来)。
我只是使用FreshMvvm的IOC来访问特定于平台的代码,而不是使用它。WickedW说的一切都是完全正确的。我只是稍微调整了最后一步。
而不是直接解决依赖关系:
IFileHelper fileHelper = FreshMvvm.FreshIOC.Container.Resolve<IFileHelper>();
string dbPath = fileHelper.GetLocalFilePath("CoreSQLite.db3");我使用构造函数注入:
Public class MainPageModel : FreshBasePageModel
{
public string YourLabelText { get; set;}
IFileHelper _fileHelper;
public MainPageModel(IFileHelper fileHelper)
{
_fileHelper = fileHelper
}
// This is implemented by FreshBasePageModel
public override void Init(object initData)
{
YourLabelText = _fileHelper.GetLocalFilePath(“CoreSQLite.db3”);
}
}在加载应用程序之前,一定要注册特定于平台的类:
FreshMvvm.FreshIOC.Container.Register<IFileHelper, FileHelper>();
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);我必须这样做,因为我在App.xaml.cs的构造函数中解析了我的App.xaml.cs:
public App()
{
InitializeComponent();
var page = FreshPageModelResolver.ResolvePageModel<MainPageModel>();
var navContainer = new FreshNavigationContainer(page);
MainPage = navContainer;
}@WickedW完全实现了平台特定的功能,然后我使用Michael的FreshMvvm n=2视频来计算构造函数注入,因为它是我个人需要的特性。希望这能帮助那些像我一样努力解决这个问题的人。
发布于 2017-09-26 07:17:42
内置于Xamarin表单中的DependencyService可以做生意,但是如果你只想在FreshMvvm中使用国际奥委会,你可以-
a)在Forms Init方法(IOS以下)附近注册您的平台特定类(Es)-
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
InitIoc();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
private void InitIoc()
{
FreshMvvm.FreshIOC.Container.Register<IFileHelper, FileHelper>();
}你的班级和往常一样都在平台边-
public class FileHelper : IFileHelper
{
public string GetLocalFilePath(string filename)
{
string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);然后在PCL / Forms项目中使用它时解析该类-
IFileHelper fileHelper = FreshMvvm.FreshIOC.Container.Resolve<IFileHelper>();
string dbPath = fileHelper.GetLocalFilePath("CoreSQLite.db3");
...https://stackoverflow.com/questions/39498580
复制相似问题