In the ASP.NET MVC 6, you can now use the @inject keyword. This allows you to inject a service (class) into your view. This class must be public, non-nested and non-abstract.

The @inject needs 2 “parameters” in order to work.

@inject [name of your class] [variable name that can be used in your view]

My Qoutes service

This is the class that i want to inject into my view.

using System.Collections.Generic;
using System;

namespace VSCode1.Models
    public class Quotes
        List<string> _quotes = new List<string> { 
            "Don't cry because it's over, smile because it happened",
            "Be yourself; everyone else is already taken.",
            "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe."    

        public string GetRandomQuote()
            Random r = new Random();                
            return _quotes[r.Next(0, _quotes.Count - 1)];

        public List<string> GetQuotes()
            return _quotes;

Putting it in my view

To use the service in my view, i add the inject statement on top of the view. “quotes” can be used a variable in this view and is of type “VSCode1.Models.Quotes”.

@inject VSCode1.Models.Quotes quotes


@foreach(var quote in quotes.GetQuotes())

Registering your service in your application

If i run my application, i would get an error saying that there is no service for type VSCode1.Models.Quotes.

service has not been registered

When you use @inject, the runtime will use dependency injection to inject the type you requested. So your type needs to be registered in the dependency injector. This needs to be done in the startup.cs file.

        public void ConfigureServices(IServiceCollection services)
            //other stuff ...


Now the mvc view renders without errors.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>