This video is available to students only

Using Token Service

In this lesson, we're going to use the token service we created in the last lecture

Using token service#

Now that we have created the token service, let's see how to use it in our application. We will go to the Startup class and register it inside ConfigureServices method. Previously, we had added services from other libraries; but this time, we are adding a custom service which we have created. We can do it below the authorization, services dot scoped. We are using scoped and not singleton or transient because we don't want this service to have a lifetime of the application. We want to use it and dispose it as the response is sent from our API. So let's mention the token service and import it from Infrastructure services. By adding it here, the service is ready to be used anywhere inside our API project.


But we don't want to use it everywhere; we will use it inside the Users controller. So let's go inside the Users controller, add TokenServices to the constructor, and import it. We can initialize the field from parameter, and the service is now ready to use. When the user logs in, rather than returning the entire user object, we can return a new UserDto which we created and return the Email which will be user.Email and for generating a token, we will use the token service which has a generate token method; this method will take the user, so we can pass it. We see an error because in our method, we are returning User but we want to return UserDto instead. Now the error is gone.

Start a new discussion. All notification go to the author.