Skip to content

Adds support for multiple implementations to Xamarin.Forms's DI system

License

Notifications You must be signed in to change notification settings

Tommigun1980/Xamarin.Forms.MultiDependencyResolver

Repository files navigation

Xamarin.Forms.MultiDependencyResolver

Adds support for multiple implementations to Xamarin.Forms's DI system

NuGet package available at https://www.nuget.org/packages/Xamarin.Forms.MultiDependencyResolver/

Intro

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.

Usage

Setup

  1. Register IMultiDependencyResolver with Xamarin's DI system:
DependencyService.Register<MultiDependencyResolver>();
  1. Create a shared interface for the relevant services:
interface IMySharedInterface { }

And implement it in your implementations normally:

class MyService1 : IMySharedInterface { }
class MyService2 : IMySharedInterface { }
  1. Register your dependencies with Xamarin's DI system normally:
DependencyService.Register<MyService1>();
DependencyService.Register<MyService2>();
  1. Register your implementations with the multi dependency resolver:
var multiDependencyResolver = DependencyService.Get<IMultiDependencyResolver>();

multiDependencyResolver.Register<IMySharedInterface, MyService1>();
multiDependencyResolver.Register<IMySharedInterface, MyService2>();

Resolving implementations

There are two ways of getting the enumeration of implementations for any registered interface.

  1. 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.

  1. Get them from the multi dependency resolver directly:
var implementations = DependencyService.Get<IMultiDependencyResolver>().Get<IMySharedInterface>();

About

Adds support for multiple implementations to Xamarin.Forms's DI system

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages