Categories
.NET

DependencyService for all

I was recently looking at migrating some code from Xamarin Forms to Uno Platform and one of the big changes when moving from Xamarin Forms to .NET 6 and later is a move towards using Microsoft.Extensions.DependencyInjection on all flavours of .NET. The key difference between this approach and DependencyService is that you have one shot to add your dependencies at the beginning of your app’s lifecycle. The DependencyService was more flexible as you could add registrations at any time before instantiating them. This makes it handy for apps which dynamically load optional areas of functionality.

I therefore took the Xamarin code and updated it and built it for .NET 6.0 so it will run on any .NET flavour with no dependencies. I removed a bunch of functionality related to handling Renderers since that was a very specific use-case and instead added support for any constructor parameters for already registered types. This allows you to pass services into your view models with no messy code. The only requirement is that your class has a single constructor, and all the types passed in as parameters have already been registered with DependencyService prior to calling Get<T>().

The result is a small NuGet package and the source is hosted on GitHub. Now, of course, this is not going to be the best approach for everyone but it provides another option when migrating from Xamarin Forms and it’s good to have choices when migrating legacy code.

By Peter Foot

Microsoft Windows Development MVP