mvvmxamarinxamarin.formsfreshmvvm

Xamarin Forms: IOC in FreshMvvm


I am using Freshmvvm for my Xamarin forms project. I am using a camera and want to use platform specific features. So, I was wondering how can I use IOC controls to use platform specific feature.

Freshmvvm.FreshIOC.Container.Register<ICamera,Camera>();

If I call this code from the App class, Should I need to have camera class in both iOS and Android projects, if yes then how to let the app class know we want to implement a Camera class of one specific platform? or is there a better way to use IOC control and inject the interfaces into the contructors of the page models(view models) when we want to use it ?


Solution

  • I think what you're after is the Dependency Service. This enables you to access native feature.

    This way you have to create an interface in your shared code for instance ICamera.

    public interface ICamera
    {
       void TakePicture();
    }
    

    Now you can implement this interface in the platform specific projects.

    For instance on iOS you might implement it like this:

    public class CameraImplementation : ICamera { public void TakePicture() { // iOS code here } }

    Now the key here is how you register this. You can do this by adding a tag like this above your namespace of the platform specific implementation, like this:

    [assembly: Xamarin.Forms.Dependency (typeof (CameraImplementation))]
    namespace yourapp
    {
       // CameraImplementation class here
    }
    

    The same goes for Android. If you keep the naming the same you can even copy and paste this tag.