Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

DbContext is getting disposed - Dependency Injection EF Core (Simple App)

$
0
0

Hello everyone! I've been searching for a while, but I haven't spot anything unusual... Maybe some configuration I've been missing? I'm injecting a dependency file which at the same time contains an injected DbContext. Problem is that the context is being disposed before I can access it.

The flow is at follows:

User access HomeController. Sends email to the RegisterEmail method. RegisterEmail method works with an injected RegisterEmail object, which at the same time has an injected EmailContext. 

Whenever I'm in the CheckIfEmailExists method I receive an error that it has been disposed.

Here's my code:

HomeController.cs

 public class HomeController : Controller
    {
        private readonly IRegisterEmail _registerEmail;
        public HomeController(IRegisterEmail registerEmail)
        {
            _registerEmail = registerEmail;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult RegisterEmail(RegisterInputViewModel model)
        {
            if (!ModelState.IsValid)
                return View("Index",model);
            TempData["msg"] = _registerEmail.NewEmailRegistration(model.Email);

            return RedirectToAction("Index");
        }
    }

RegisterEmail.cs

ublic class RegisterEmail : IRegisterEmail
    {
        private readonly ILogger _logger;
        private readonly EmailContext _emailContext;
        private string _error;

        public RegisterEmail(ILogger<RegisterEmail> logger, EmailContext emailContext)
        {
            _logger = logger;
            _emailContext = emailContext;
        }

        private async Task<bool> AddEmail(Register email)
        {
            _emailContext.RegisterDb.Add(email);
            try
            {
               await _emailContext.SaveChangesAsync();
               return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                _error = ex.Message;
                return false;
            }

        }

        public async Task<string> NewEmailRegistration(string emailAddress)
        {
            if (string.IsNullOrWhiteSpace(emailAddress))
                throw new ArgumentException("Email Address can't be blank or null");

            if (await CheckIfEmailExists(emailAddress))
                return "Email exists!";

            return await AddEmail(Register.NewRegistration(emailAddress))
                    ? "Email has been added"
                    : $"The following error has occured: {_error}";

        }



        private async Task<bool> CheckIfEmailExists(string emailAddress)
        {
            try
            {
                return await _emailContext.RegisterDb
                                   .FirstOrDefaultAsync(x => x.Email.ToLowerInvariant() == emailAddress.ToLowerInvariant())
                                   != null;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                throw;
            }
        }

        
    }

IRegisterEmail.cs:

    public interface IRegisterEmail
    {
        Task<string> NewEmailRegistration(string emailAddress);
    }

Startup.cs:

 public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            

            //Enable Session Before MVC
            services.AddMemoryCache();
            services.AddSession();

            //DI here:
            services.AddTransient<IRegisterEmail, RegisterEmail>();
            services.AddDbContext<EmailContext>(options =>
                   options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            // Add framework services.
            services.AddMvc();
            services.AddLogging();
        }

        // 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)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

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

Anything unusual? 


Viewing all articles
Browse latest Browse all 9386

Trending Articles