skip to content
Stylized letter A in teal with pink sparkle accents Khalid Abuhakmeh

ASP vNext Dependency Injection Lifecycles

/ 2 min read

Found this post helpful?

Buy me a coffee
Table of Contents

ASP.NET has seen an evolution when it comes to dependency injection. It first started with no acknowledgment in versions 1 to 3. Then ASP.NET MVC 4 introduced the IDependencyResolver interface. With ASP vNext we see an out of the box inversion of control container that works. The introduction of a working IoC container means you can probably get 90% of what you need without having to resort to pulling in your favorite library as a dependency (Go Structuremap!).

Startup.cs

In the ASP vNext samples we see that registering services is done using the IServiceCollection interface, with extension methods doing the heavy lifting.

public void ConfigureServices(IServiceCollection services)
{
// Add EF services to the services container.
services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<ApplicationDbContext>();
// Add Identity services to the services container.
services.AddDefaultIdentity<ApplicationDbContext, ApplicationUser, IdentityRole>(Configuration);
// Add MVC services to the services container.
services.AddMvc();
}

In the sample above, we add the services for Entity Framework, ASP.NET Identity, and MVC. In addition to using extension methods, you can register services one at a time. Before you register a service, it is important to understand the Lifecycles offered by ASP.NET MVC out of the box.

Singleton

An object registered as a Singleton will be instantiated once and be available for the entire lifetime of your application. For example, a logger may be implemented as a singleton.

Scoped

An object registered as Scoped will be instantiated once per request and be available for the lifetime of the request. Your database access layer is a great candidate to be scoped if you are utilizing the unit of work pattern.

Transient

An object registered as Transient will be instantiated every time IT is requested. If you need to create a unique object utilizing a deep dependency graph, then you might consider registering the object as transient.

Conclusion

It is important to know how your objects will hang around when created by an IoC container, the first step is understanding the Lifecycles available to you. Clearly the implementation of extension methods as registration tools is a big part of the ASP vNext style, so I suggest you start getting comfortable with the pattern. Good luck injecting your dependencies.

Related Posts