Search code examples
inversion-of-controlfactory-patternmvvmcross

Constructor Injection to access service


Is there a better way to consume a service in mvvmcross by constructor injection? For example, I have my object in a plugin implementation

public class MyObject : IMyObject
{
   public MyObject (int id) 
   {
      _id = id;
   }
}

and want to consume it somewhere the portable core (in the buisness layer) like this :

public void ConsumeTheService()
{
    int i = 50;
    var myObject = this.GetService<IMyObject>(i);
}

Actually, I only use a setter to get my id back in the implementation.


Solution

  • Following your update... if you are asking about how to get:

        var myObject = this.GetService<IMyObject>(50);
    

    and for this to return an object which is initiaised as new MyObject(50)

    then I would instead recommend that you implement an interface

    public interface IMyObjectFactory
    {
        IMyObject CreateMyObject(int i);
    }
    

    with an implementation:

    public class MyObjectFactory : IMyObjectFactory
    {
        public IMyObject CreateMyObject(int i)
        {
            return new MyObject(i);
        }
    }
    

    you can then register this IMyObjectFactory with IoC