locked
Service Containers RRS feed

  • Question

  • User-305496339 posted

    Hello Friends,

    Would anyone mind explaining a real world use case where you would use each of the methods AddSingleton, AddScoped, and AddTransient. Thanks !!!

    Sunday, May 19, 2019 6:12 AM

Answers

  • User1120430333 posted

    https://dotnetcoretutorials.com/2017/03/25/net-core-dependency-injection-lifetimes-explained/

    I always use transient for objects I have created, becuase I always want a new instance of the objects everytime the Web solution is used, highlighted in the MVC and WebAPI Startup.cs. 

    using System;
    using System.IO;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.FileProviders;
    using Microsoft.Extensions.Logging;
    using ProgMgmntCore2UserIdentity.Data;
    using ProgMgmntCore2UserIdentity.Models;
    using ProgMgmntCore2UserIdentity.WebApi;
    using Serilog;
    
    namespace ProgMgmntCore2UserIdentity
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
                Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
    
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(
                        Configuration.GetConnectionString("DefaultConnection")));
                services.AddDefaultIdentity<IdentityUser>()
                    .AddEntityFrameworkStores<ApplicationDbContext>();
    
    
                //Password Strength Setting
                services.Configure<IdentityOptions>(options =>
                {
                    // Password settings
                    options.Password.RequireDigit = true;
                    options.Password.RequiredLength = 8;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireUppercase = true;
                    options.Password.RequireLowercase = false;
                    options.Password.RequiredUniqueChars = 6;
    
                    // Lockout settings
                    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
                    options.Lockout.MaxFailedAccessAttempts = 10;
                    options.Lockout.AllowedForNewUsers = true;
    
                    // User settings
                    options.User.RequireUniqueEmail = true;
                });
    
                //Seting the Account Login page
                services.ConfigureApplicationCookie(options =>
                {
                    // Cookie settings
                    options.Cookie.HttpOnly = true;
                    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
                    options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
                    options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
                    options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
                    options.SlidingExpiration = true;
                });
    
                services.AddSingleton<IFileProvider>(
                    new PhysicalFileProvider(
                        Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));
    
                //Models
                services.AddTransient<IProjectModel, ProjectModel>();
                services.AddTransient<ITaskModel, TaskModel>();
                services.AddTransient<IModelHelper, ModelHelper>();
                services.AddTransient<ICacheModel, CacheModel>();
    
                //WebApis
                services.AddTransient<IWebApi, WebApi.WebApi>();
    
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services, ILoggerFactory loggerFactory)
            {
                loggerFactory.AddSerilog();
    
                app.UseExceptionHandler("/Error/Error");
               
                app.UseStaticFiles();
    
                app.UseAuthentication();
                
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }
    
    using System.Net;
    using DAL;
    using Entities;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Diagnostics;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Serilog;
    
    namespace ProgMgmntCore2Api
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
                Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                //DAL
                services.AddTransient<IDaoProject, DaoProject>();
                services.AddTransient<IDaoTask, DaoTask>();
                services.AddTransient<IDaoCache, DaoCache>();
    
                //Configuration
                services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
    
                // Add framework services.
                services.AddMvc(options =>
                {
                    options.Filters.Add(new ErrorHandlingFilter(Configuration));
    
                });
    
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory, IApplicationLifetime appLifetime)
            {
                //this is used by Postmon and Global Exception handelling to show exception.
                app.UseExceptionHandler(
                    options =>
                    {
                        options.Run(
                            async context =>
                            {
                                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                                context.Response.ContentType = "text/html";
                                var ex = context.Features.Get<IExceptionHandlerFeature>();
                                if (ex != null)
                                {
                                    var err = $"<h1>Error: {ex.Error.Message} </h1>{ex.Error.StackTrace } {ex.Error.InnerException.Message} ";
                                    await context.Response.WriteAsync(err).ConfigureAwait(false);
                                }
                            });
                    }
                );
    
    
                loggerfactory.AddSerilog();
                app.UseHttpsRedirection();
                app.UseMvc();
    
            }
        }
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, May 19, 2019 8:55 PM