Make a class implement a Interface using Android Bindings in Xamarin

I'm developing an Android application using Xamarin. For this app, I'll need to use two .jar libraries. These libraries do exactly the same thing, the difference is only that one should be used in a production environmentand the other is for development usage.

One of the requirements for that application, is that it must have a configuration that the user can set, to specify the environment (Production or Development).

I need to interact with a class of those libraries (let's call it Foo). If I needed to create that class using C#, I would first create an interface named IFoo and then create the two classes implementing that interface, then I would use a factory to create the correct instance based on the preference that the user set. But the problem is that on the Java libraries, both of those classes inherith directly from Object, so my calling code will not be able to use an abstraction as I wanted.

I was wondering, if it's possible to use the Metadata transform to modify the generated code to make the classes implement an interface. I was able to make it work by modifing the generated code, but every time I recompile the project, I miss my modifications.

Upvotes: 0

Views: 1736

Answers (1)

Sven-Michael Stübe
Sven-Michael Stübe

Reputation: 14750

Your generated classes are partial. This means that you can extend them easily.

generated

[global::Android.Runtime.Register ("com/bar/baz/Foo", DoNotGenerateAcw=true)]
public partial class Foo : global::Java.Lang.Object {

}

addition

Add this (Foo.cs) to the folder Additions

public partial class Foo : IFoo 
{
    public void WhatEverFooDoes() 
    {
        // implement me
    }
}

IFoo can define methods that are implemented by the generated code as well. So you just have to extract the interface from one of you classes, if the signature is exactly the same.

Upvotes: 2

Related Questions