A.Pissicat A.Pissicat - 8 days ago 5
C# Question

Change method in other project

I'm working in a C# application.

I have a library used to generate matrix. For the debug I created a method

WriteToFile
. But this library is used for an application on PC and an other one on android (maybe iOS later). So I don't want to use IO in this library.

There is my solution :


  • ProjectLibrary

  • ProjectPC

  • ProjectAndroid



Actually there is a class in ProjectLibrary for the matrix

namespace ProjectLibrary
{
public class Matrix
{
public void Generate()
{
//Generate Step 1

//for the debug I want to use this method sometime
WriteToFile();

//Generate Step 2
}

public void WriteToFile()
{
//TODO
//if ProjectPC write on PC
//if ProjectAndroid write on phone
}
}
}


My question is : How can I create the method
WriteToFile
? This method have to be called in my project
ProjectLibrary
but depending on
ProjectPC
and
ProjectAndroid
it will not be the same.

Answer

Use an interface and depedency injection !

In your project library create the interface:

public interface IFileWritter
{
    void WriteToFile();
}

Then modify your Matrix class to add the dependy :

public class Matrix
    {
        private IFileWriter _writer;

        public Matrix(IFileWriter writer)
        {
             _writer = writer;
        }

        public void Generate()
        {
            //Generate Step 1

            //for the debug I want to use this method sometime
            _writer.WriteToFile();

            //Generate Step 2
        }


    }

In your Windows project then you create a Class inheriting from IFileWriter :

public class WindowsFileWriter : IFileWriter
{
    public void WriteToFile()
    {
        //Your windows code
    }
}

Then you do the same in your Android Project :

public class AndroidFileWriter : IFileWriter
{
    public void WriteToFile()
    {
        //Your android  code
    }
}

And then when you need your matrix class in Android you just have to call it this way :

AndroidFileWriter myAndroidFileWriter = new AndroidFileWriter();
Matrix myMatrix = new Matrix(myAndroidFileWriter );
myMatrix.Generate();

And in Windows :

WindowsFileWriter myWindowsFileWriter = new WindowsFileWriter();
Matrix myMatrix = new Matrix(myWindowsFileWriter );
myMatrix.Generate();

Even better (from my point of view) if you use some Mvvm framework you can register in the IOC your implementation of IFileWriter !

For example with MvvmCross this would give you :

Mvx.Register<IFileWriter, AndroidFileWriter>(); //in your android project start

and

Mvx.Register<IFileWriter, WindowsFileWriter>(); //in your windows project start

And then calling Mvx.Resolve().Generate() in your core project

Comments