Getting Started with Dependency Injection in Xamarin.Forms

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're going to take a look at the built-in support for dependency injection or dependency services in xamarin forms this gives you the ability to tap into native functionality easily from your shared code or just create really reusable interfaces for your application that are really testable so tune in [Music] hey everyone i'm james montemagno i'm back with another xamarin 101 video if you haven't checked out the series right up there i'll put it over there in a little card i've been building out an application from scratch showing you how to incorporate beautiful awesome features of xamarin forms into native ios and android applications all built with c-sharp and visual studio we've come quite a long way in our application we've done a lot of back-end services databases theming and a lot more and today we're talking about dependency injection or dependency services with xamarin forms luckily for us xamarin forms has this built in out of the box and it's really really fast and it's uh it's compiled up and it's got some really nice ways of sort of abstracting your code now if you're new to c sharp or want to know what dependency injection is what it does is it enables you to use a powerful feature of a c sharp called interfaces and an interface is just a definition of what methods or properties are going to be inside of a class so for example we have a coffee service and right now it's a bunch of just static methods that we can randomly call but we may want it to be a specific interface so we could swap out a database with another database or a web call so we create an interface in an interface we could describe methods or properties so get a coffee add a coffee remove a property and what's nice here is that with an interface if multiple classes implement that interface we know exactly what is going to be in that definition and this again is really nice if we do want to swap out our database with a different database want to make a web request we want to use something else it's a really nice way of creating reusable interfaces or definitions of what these classes are going to be the side effect here is that it also enables you to create sort of testable code you can test these interface methods and properties inside of your unit test without having to construct objects and you can use a bunch of different test frameworks that are out there like n unit and x unit and interfaces are very popular in fact with don and maui all of the controls are interfaces too so they're they're kind of all in that sort of awesomeness which is kind of cool also it enables you to create a way of tapping into native functionality so for example you may want to have like a toast service so something like pops up a little notification which we'll implement here together well that doesn't exist in shared code like that coffee service is shared code but how do i reach android or ios or windows or mac functionality you can create an interface and then implement it on each platform and like i said the nice thing is xamarin forms has this all built in so let's get started okay the first thing here is actually have a coffee service like i mentioned earlier we have a few coffee services but you know the one that we're going to create today is this coffee service and it's going to have a few methods such as an init an add coffee remove coffee it also has get coffee things like that now technically this init method doesn't need to be on the interface because it's not even public interfaces are really just going to describe public facing methods that we want so to get started here we're actually going to use visual studio to generate the interface so i'm just going to go ahead and remove these statics because without that visual studio won't know how to refactor it now i'm going to tap on this coffee service right click and say quick actions and refactorings and we can see over here extract interface is right here for us that wouldn't be there if everything was static but since it's just a normal class we can extract that interface here it's going to ask us what we want so we're going to select all which is good i coffee service that sounds about right and let's see add coffee get coffee get coffee with an int and remove coffee notice that it did find only our public methods that are in here and that's perfect so let's go ahead and do that it's going to create a new file called i coffee service all right let's take a look at i coffee service there it is so there's i coffee service we want to do anything it's created it all for us we could have created this manually if we wanted to too but here is our i coffee service here it has task add coffee so name roaster get coffee get coffee remove coffee we go back into our coffee service actually nothing here has changed all it did was implement i coffee service now if i go and add another method over here like task do something all right and go back into my coffee service we will see that now we get a red squiggly and it will tell us that we want to implement that interface and then it will implement it here for us now we're not going to do that because we don't have that but showing you that when you add new interfaces you you need to implement those with c 9 you can actually do default implementations which is kind of cool too which is a nice feature now the cool part here is that actually our internet service coffee actually implements the same stuff has like get it has you know add coffee it has removed coffee so we could actually implement that interface here too and we could then create reusable sort of ways of saying what coffee service do i want let's just stick with the one keep it simple we now have our coffee service now there's two ways of telling xamarin forms that for this interface i would like to use this coffee service what we do is on top of the namespace we can do an assembly dependency over here and bring in xamarin forms boop and the dependency shows us what type do we want to bring in so here we'll say type of and we'll say coffee service so we're saying create a dependency for the dependency service that's built in with the coffee service now what this does is this sort of assembly attribute will automatically detect any interfaces that this class implements and enable us to get one basically a coffee service globally back just from that single interface we could also get just that class back if we want to because it'll also register it there for us now i also want to mention that some people don't like these kind of assembly exports you can actually put them anywhere so if you wanted to put them in your assembly info with all of your export fonts you could do that too some people like to do this inside of the code when the app starts so they can see all their dependencies so instead of putting that you know dependency there we can come in here and we can actually say dependency service dot and notice that there is a get a register a register singleton and a resolve so there's these three different ones that are in here so register enables us to register any class a single 10 is obviously a singleton so you only get one instance of it back and you can resolve those back the resolve singleton resolve and register single 10 or newer but what i can do here is i can say i coffee service here as my type that i want to register and then here um oh that's it actually just say i i coffee service or just coffee service and that will go ahead and do it so it'll just register it all automatically so very very similar uh there notice that there's a single class but here also implementation so that's actually probably what i need to do which is i coffee service and then coffee service coffee service there we go so in this case i had the ability to register just the class or the implementation and the actual coffee service there so it's sort of up to you i personally prefer just to keep them right in line right here with this nice assembly export and go to town there so now let's say we want to get access to this well that's actually pretty easy to do so if we go into our view models where we actually had my my coffees if you remember here we had our coffee service remove coffee so what we're able to do now that we've registered this specific coffee service we can come up here and i can say i coffee service i'll say coffee service just like that and in my constructor i'm going to say coffee service equals all right then what i'm going to do is say dependency service just like we saw before but i'm going to say get and i'm going to ask to get back in i coffee service now i want you to look here that there is specifically a parameter that you can pass in which is the dependency fetch target and that fetch target is either a global instance or a new instance here so if you want to get a new instance of this coffee service every single time you can do that for this the default is the global instance because it will be the same exact database every single time which is what we want to use in this case here so if we want to share services between different view models that's how you're going to do it so now all we got to do is come down here simply say remove right there we'll say wait coffee service remove coffee and here await coffee service so it's no longer a static and pretty much there it is i think at this point yeah there's another one so here is a good example is we have another page that adds a coffee to the database so we can do the same exact thing take that i coffee service over here take this code that got gets the global dependency there we go and then what we can do is just drop that down so it's no longer static and there we have it now let me go ahead and compile this up just to make sure we got all the references there looks like we have one more which is this coffee service down over here up the details page perfect so again we're going to do the same thing here i coffee service put this here when i create this page we're going to get a reference to it and then we'll go over into this page add it here and again drop down to not use the singleton now at this point we're ready to go because we have our entire coffee service it's been created it is injected and sort of the injection part of it is we're taking that class and injecting it into the dependency service which can then go and get it later back for us and we're using the same instance of it so once it's been created it'll only create one and it'll keep it in memory and if for some reason the garbage collector comes by and sweeps it away well don't worry because next time you get it back it will go ahead and create a new one for you so now we're going to go ahead and compile this up and then deploy it to our android device let's give it a second here all right perfect so we have our coffees right here let's go ahead and go into my coffee which is going to be the coffees from the database which there are none currently because i just installed this application fresh which is good let's go ahead and add this in so i'm going to say motts and then i'm going to say new coffee over here hit save hit refresh here and then we should get that coffee back from our database right there which is pretty awesome i can go of course and now go in and let's say i went ahead and remove this and open it up again so let's go ahead and open up the my coffee application there we go and what we should see is if i go into my coffees now refresh it up and then we will go ahead and see that there's my coffee it's using the same exact dependency injection service everything there now i will say this a lot of people keep asking me like how come you just don't refresh the you know coffees when you hit the web or when you come in i could have done that on this on appearing and i should do that and get the coffees and show them but you know they're there when i pull the refresh and i'm good to go i could tap on one get some information oh well we're good to go all right so now that we have that in place let's say we want to you know actually come in and do a little alert whenever i pull the refresh and put a little toast message up right like oh coffee's refreshed we can do that by coming in and creating another interface here i'm going to say new item and i'm going to say let me create a new interface and i'm going to say i toast all right and here we're going to make this a public interface and we're going to call it the uh hey we're going to put in a uh i don't know i guess a void of make toast string message all right so that's going to be our one method that we have is we're going to implement this somewhere now built into android is toast notifications which is quite nice so what i can do is come into my android application here so i'm going to come into my main activity and let's just go ahead and come in and create a new class public class toaster and i'm going to implement i toast all right we're going to bring in that here we're going to bring in and implement the interface and now all i need to do is say toast dot and then here make text and then we'll say we'll say platform dot over here so we need to get access to the context using xamarin essentials dot app context the id which would be a string that we want to do but we can actually just pass in a string over here which is going to be the message and then i'm going to do toastlength.long.show all right so i actually tapped into some android specific you know implementations here and just like you'd assume i can come up and say assembly and i'll say dependency right here i'm going to bring in that xamarin.forms namespace i'm going to say type of toaster all right again bring in this namespace now whenever i go ahead and add something in here into the database or pull the refresh let's do that pull to refresh it'll go ahead and do it so let's go into the my coffee view model now in this case we want to make sure that that toast is that toaster exists i haven't implemented it on ios maybe i never will but let's say over here when i'm done i want to make sure that it's not null so what i can do is i can say dependency service dot get i toaster or i toast right and then i'm going to do a question mark dot over here and what this does is it's no coalescing so it comes in and it says you know if this toast exists this toaster exists call the method else stop and don't do anything which is really really nice so here i'll say refreshed okay look at that so very very simple so if this thing over here is no if i'm on i'm on windows or i'm on ios it's not going to do anything else if it exists it will go ahead and pull it up and do the toast that says refreshed and then we're good to go so this is a really great way of tapping into that native functionality in case you know xamarin essentials doesn't give it to you it's also nice because you can then implement a fake eye toast in your unit test for example and then you don't have to worry about it running on an actual platform you can describe what it does let's go into my coffee i'm going to pull the refresh everything is working correct pull it over there it is refreshed right there let me do it one more time so we can see it it's now tapping into that native functionality via the dependency service and there you have it it's really just that easy to start using dependency injection inside of your ios android windows mac application with xamarin forms now i know there's probably a lot of questions around ioc or inversion of control this is something that you pass interfaces into a constructor and then it creates it automatically i'll link to a blog post in which i outline sort of the microsoft extensions way of doing this which is similar to asp.net core and is which is how also.net maui will work so this is one of those things where i don't know if the dependency service will come along for the ride but there'll be a new way of doing it done at maui which is even smoother which is really exciting too but i do like that the dependency service is just right there there are a bunch of awesome third-party libraries out there that you can use i just want to show you what's in the box no need to install any other new gets or anything like that and it's readily available for you hopefully you found this video and of course all my videos super helpful in building your xamarin forms applications out and to get them ready for donna maui if you did like the video give it a thumbs up it goes into the google algorithm of goodness of course it recommends it to other individuals watching stuff on youtube and of course subscribe and hit that notification bell that helps you stay up to date with videos that i'm putting out here on my channel if you want a little bit more you can also follow me on twitter at jamesmontamagno and subscribe to my brand new weekly newsletter you can go to newsletter.montemagno.com it's in the show notes below and i'll put a banner right here over my face that shows it which is quite cool i just started that back up and i love to have you you know part of that journey with me as i do weekly newsletters talking about all cool things in the world of tech all right well that's going to do it for this week's episode i hope you enjoyed it so until next time i'm james montemagno and thanks for watching you
Info
Channel: James Montemagno
Views: 7,075
Rating: undefined out of 5
Keywords: dependency injection, di, ioc, dependency, injection, xamarin.forms, xamarin, xamarin forms, ios, android, uwp, autofac, prism, dependency service, inversion of control, testable code, services, nunit, xunit
Id: 6CwQKqMpUFk
Channel Id: undefined
Length: 19min 41sec (1181 seconds)
Published: Thu Jun 10 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.