Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin DependencyService with Parameterized Constructor

How I can use Xamarin Forms DependencyService to inject dependency through Parameterized Constructor ?

like image 858
Stephan Ronald Avatar asked Jun 13 '19 18:06

Stephan Ronald


1 Answers

Answer

You cannot.

The assembly attribute implementation only works with default constructors (aka parameterless constructors), e.g.[assembly: Dependency(typeof(MyClass))].

The run-time implementation also only works with default constructors (aka parameterless constructors), e.g Xamarin.Forms.DependencyService.Register<T>()

Edit: (Highlighting Nitha Paul's question in the comments): Xamarin.Forms.DependencyService is a Service Locator, not an IoC Container, and Service Locators cannot do Dependency Injection.

Recommendation

I recommend using TinyIoC for your Dependency Injection.

Here are performance metrics showing TinyIoC is the fastest IoC tool for Xamarin.Forms: https://github.com/jsuarezruiz/xamarin-forms-perf-playground#ioc

public class App : Xamarin.Forms.Application
{
    public App()
    {
        // Register DI
        TinyIoCContainer.Current.Register<INumber>(new NumberClass(42));
        TinyIoCContainer.Current.Register<MyClass>();

        // Resolve DI
        var myClass = TinyIoCContainer.Current.Resolve<MyClass>();
        Console.Writeline(myClass.ToString()); //42

    }
}

public class MyClass
{
    readonly INumber _number;

    public int MyClass(INumber number)
    {
         _number = number;
    }

    public override ToString() => _number.Num;
}

public class NumberClass : INumber
{
    public NumberClass(int number)
    {
        Num = number;
    }

    public int Num { get; }
}

public interface INumber
{
    int Num { get; }
}
like image 96
Brandon Minnick Avatar answered Nov 09 '22 10:11

Brandon Minnick