What is the difference between addtransient vs addsingleton vs addscoped in asp.net core mvc by Sagar Jaybhay

addtransient vs addsingleton vs addscoped in asp.net core mvc explained by Sagar Jaybhay

Explained different type of dependency injection in asp.net core mvc.

To inject service in the controller we use constructor and by using this we inject object of service in controller. Below is our HomeController in this we inject IStudentRepository in Controller by using constructor injection.

public class HomeController : Controller
    {
        private IStudentRepository _repository;

        public HomeController(IStudentRepository repository)
        {
            this._repository = repository;
        }

        //[Route("")]
        //[Route("~/")]
        //[Route("[action]")]
        public ViewResult Index()
        {
            var v = _repository.GetAllStudent();
            return View(v);
        }

       // [Route("[action]")]
        public ViewResult List()
        {
            var v = _repository.GetAllStudent();
            return View(v);
        }
      //  [Route("[action]/{id?}")]
        public ViewResult Details(int id)
        {
            HmDetailsVM hmDetailsVM = new HmDetailsVM();
            hmDetailsVM.student = _repository.GetStudents(id);
            hmDetailsVM.DivisonOfStudent = "9-A";
            ViewBag.TitleNew = "Student Info";
            return View(hmDetailsVM);
        }

        [HttpGet]
        public ViewResult Create()
        {
            return View();
        }
       
        [ActionName("CreateStudent")]
        [HttpPost]
        public IActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                var st = _repository.AddStudent(student);
                return RedirectToAction("Details", new {id = st.StudentId});
            }

            return View("Create");
        }

    }

To inject service in a view we need to use Inject to insert it into view. Below is code for that

@model Student
@inject IStudentRepository StudentRepository
@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Student</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="CreateStudent">
            @*<div asp-validation-summary="ModelOnly" class="text-danger"></div>*@
            <div class="form-group">
                <label asp-for="StudentId" class="control-label"></label>
                <input asp-for="StudentId" class="form-control" />
                <span asp-validation-for="StudentId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="FullName" class="control-label"></label>
                <input asp-for="FullName" class="form-control" />
                <span asp-validation-for="FullName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address" class="control-label"></label>
                <input asp-for="Address" class="form-control" />
                <span asp-validation-for="Address" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Division" class="control-label"></label>
                <select asp-items="@Html.GetEnumSelectList<Divi>()"></select>
            </div>
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <div class="form-control">
        <label class="col-form-label">
       Total Number Of Students:- @StudentRepository.GetAllStudent().Count()
        </label>
    </div>
</div>

<div>
    <a asp-action="List">Back to List</a>
</div>

Inject service in view in asp.net core mvc

Now you can see below how we add the repository or service in our MVC application below is the code for that which is present in the startup.cs file. In this below code we use AddSingleton Method to add/ register the service.

public class Startup
    {
        private readonly IConfiguration _config;

        public Startup(IConfiguration configuration)
        {
            _config = configuration;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            
            services.AddSingleton<IStudentRepository,StudentRepo>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            DeveloperExceptionPageOptions pageOptions = new DeveloperExceptionPageOptions();
            pageOptions.SourceCodeLineCount = 10;
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage(pageOptions);
            }

            app.UseStaticFiles();
            app.UseHsts();
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "default", template: "sagar/{controller=Home}/{action=Index}/{id?}");
            });

            // app.UseMvc();

            app.Run(async (context) => 
            {
            //    throw new Exception("Error occured");
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }
    }
addsingleton in asp.net core mvc

AddSingleton

Now you can see in the above case we inject the service in Controller, as well as View also above given view, is Create View. In this we see in startup.cs file or startup class we register our service by using AddSingleton method which means even if we insert service or repository in 2 places Controller and View it will create only one instance of that repository.

So in AddSingleton method, only one instance is created and which is served all Http/https requests throughout the application.

AddScoped

In this method, we get the same instance within scope of given Http/https request. But if any new Http/https request coming it will create new instance.

public class Startup
    {
        private readonly IConfiguration _config;

        public Startup(IConfiguration configuration)
        {
            _config = configuration;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            
            services.AddScoped<IStudentRepository,StudentRepo>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            DeveloperExceptionPageOptions pageOptions = new DeveloperExceptionPageOptions();
            pageOptions.SourceCodeLineCount = 10;
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage(pageOptions);
            }

            app.UseStaticFiles();
            app.UseHsts();
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "default", template: "sagar/{controller=Home}/{action=Index}/{id?}");
            });

            // app.UseMvc();

            app.Run(async (context) => 
            {
            //    throw new Exception("Error occured");
                await context.Response.WriteAsync("Hello Sagar Jaybhay3");
            });
        }
    }

addscoped in asp.net core mvc

AddTransient

In this method every time the new instance will be created for every request like scoped method but if method call is in the scope then also new service object will be created.

Means whether it is same scope on same Http call or different Http call or request every time it will create different object.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            
            services.AddTransient<IStudentRepository,StudentRepo>();
        }
addtransient in asp.net core

Means in our example controller and view both have separate instances of service object.

Service Type In the scope of same Http request Different Http request
Singleton The same Instance of repository servedThe same Instance of repository served
Scoped Same Instance Different Instance
Transient Every time New Instance Every time New Instance

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Related posts