Adds support for multiple implementations to Xamarin.Forms's DI system
NuGet package available at https://www.nuget.org/packages/Xamarin.Forms.MultiDependencyResolver/
Xamarin.Forms's DI system is quite limited, where one of the major missing features is support for registering multiple implementations for an interface. ASP.NET Core (https://edi.wang/post/2018/12/28/dependency-injection-with-multiple-implementations-in-aspnet-core) and many other implementations support this feature.
This package adds support for multiple implementations to Xamarin.Forms's built-in DI system by extending its existing functionality.
- Register IMultiDependencyResolver with Xamarin's DI system:
DependencyService.Register<MultiDependencyResolver>();
- Create a shared interface for the relevant services:
interface IMySharedInterface { }
And implement it in your implementations normally:
class MyService1 : IMySharedInterface { }
class MyService2 : IMySharedInterface { }
- Register your dependencies with Xamarin's DI system normally:
DependencyService.Register<MyService1>();
DependencyService.Register<MyService2>();
- Register your implementations with the multi dependency resolver:
var multiDependencyResolver = DependencyService.Get<IMultiDependencyResolver>();
multiDependencyResolver.Register<IMySharedInterface, MyService1>();
multiDependencyResolver.Register<IMySharedInterface, MyService2>();
There are two ways of getting the enumeration of implementations for any registered interface.
- The recommended way is to get them from the Xamarin.Forms's built-in DI container:
var implementations = DependencyService.Resolve<IEnumerable<IMySharedInterface>>();
Note that you have to use DependencyService.Resolve, DependencyService.Get won't work.
In order to use this approach you have to enable it by calling this in your code once:
DependencyService.Get<IMultiDependencyResolver>().RegisterDependencyServiceResolver();
This registers a Xamarin.Forms DependencyResolver (to allow piggybacking on the DependencyService), so if your app requires the DependencyResolver for something else, see below.
- Get them from the multi dependency resolver directly:
var implementations = DependencyService.Get<IMultiDependencyResolver>().Get<IMySharedInterface>();