Tel Map

Blog

Dependency Injection in ASP .NET 5 MVC 6

With ASP .NET 5 MVC 6 you do not have to rely on external Dependency Injection (DI) libraries any more. It comes with it’s on onboard DI. I will now demonstrate how to set up Dependency Injection for using Entity Framework 7 DbContexts within Controllers.

Register Service

For simplicity of this example I will not create a separate interface for my DbContext or implement a repository pattern for accessing the database. In bigger projects, I strongly recommend to do so, however. If you want to keep it simple like me you can directly register the DbContext for later on injection into Controllers in the class Startup.cs.

Typically you create an interface like IAppContext and inject the concrete implementation you want to use. This way if you want to exchange the actual implementation of the interface, this is much easier.

But as you can see you can also directly register the DbContext without using a separate interface.

Besides AddTransient there are also a couple of other methods, one can use to register a service for injection.

  • AddTransient
    • This will create a new instance each time a component asks for it.
  • AddInstance
    • This will always deliver the same instance provided by this method.
  • AddSingleton
    • This will generate one single instance and each component will get the same instance if it asks for it.
  • AddScoped
    • This will deliver the same instance within the scoped container.

Using Dependency Injection in a Controller

In order to use Dependency Injection you simple have to add the interface or in this instance AppContext to the constructor of a Controller. On construction of the Controller the Dependency Injection will simply provide the corresponding implementation you specified in ConfigureServices method.

As you can see AppContext is simply added as a parameter to the constructor and then assigned to a read only field. Later on the DbContext can be used in the Get method to count the number of images in the database. The Dispose method of the context is automatically called afterwards. Please also note that Controllers in ASP .NET 5 MVC 6 now all derive from Controller (in contrast to ApiController etc). They can either return a result and act a REST controller or a View for rendering.

Summary

This article demonstrates how to use the new Dependency Injection within ASP .NET 5 to inject a database context into a controller. In the next article we will show how to set up authentication using the ASP .NET Identity and Entity Framework.

 

 

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert