Home > 5.0, ASP.NET, vNext > Dependency Injection in ASPNET VNext (RC1)

Dependency Injection in ASPNET VNext (RC1)

This article will document how to do dependency injection for vNext

1. Create the class to be injected (https://gist.github.com/kwanann/a0363add23870a949334)

image

2. Configure startup.cs (https://gist.github.com/kwanann/7bced8e22fec229bd0be)

image

There are 4 methods of adding to services

AddTransient: It will create a new instance each time it is accessed. e.g when I call it from the MVC Controller and from frontend MVC code, I will get 2 independent instances

AddScoped: It will create a new instance for the particular request, e.g when I call it from MVC Controller and frontend MVC Code, it’s the same instance. However it does not survive across different OWIN middleware

AddSingleton: Creates a single instance for all requests

AddInstance: Creates a single instance for all requests, but the constructor is left to the developer

3. If you need to call it from within the MVC Controller (https://gist.github.com/kwanann/c987314e0eecdab20a7b)

image

Inject the interface you need into the constructor and then assign it to a local variable. You may then use it however you wish

Categories: 5.0, ASP.NET, vNext
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: