How I can use Xamarin Forms DependencyService to inject dependency through Parameterized Constructor ?
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.
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With