0
votes

Have been having trouble adding a service worker. I've been getting this error, if anyone can steer me in the right direction

An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'Assignment1.Models.ProductContext' while attempting to activate 'Assignment1.Controllers.ProductController'. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

public class ProductContext : DbContext
    {
        public ProductContext(DbContextOptions<ProductContext> options)
        
            : base(options)
        { }
        public DbSet<Product> Products{ get;set; }
        
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Product>().HasData(
                new Product { ProductId = 1, ProductName = "Computer Mouse", ProductPrice = 39.99, DateAdded = DateTime.Now },
                new Product { ProductId = 2, ProductName = "Computer Headset", ProductPrice = 49.99, DateAdded = DateTime.Now },
                new Product { ProductId = 3, ProductName = "Computer Monitor", ProductPrice = 199.99, DateAdded = DateTime.Now },
                new Product { ProductId = 4, ProductName = "Computer Mousepad", ProductPrice = 19.99, DateAdded = DateTime.Now }
                 );
        }
    }

public class ProductController : Controller
    {
       private ProductContext context { get; set; }

        public ProductController(ProductContext ctx)
        {
            context = ctx;
        }

        public IActionResult Index()
        {
            var products = context.Products
                .OrderBy(p => p.DateAdded); 

            return View(products);
        }
        [HttpGet]
        public IActionResult add()
        {
            return View();
        }
        [HttpGet]
        public IActionResult edit(int id)
        {
            return View();
        }
        public IActionResult details(int id)
        {
            return View();
        }
        public IActionResult delete(int id)
        {
            return View();
        }

        [HttpPost]
        public IActionResult edit(Product product)
        {
            return View();
        }
        [HttpPost]

        public IActionResult delete(Product product)
        {
            return View();
        }
    }

startup.cs 
 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        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.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
1
code is missing. put the entire ProductContext in there. What's wrong is you don't inject ProductContext in to the DI pipeline, but without seeing the definition I can't tell you how to inject it. - Andy
Updated, sorry about that - ro_chl
ok I see. read this: docs.microsoft.com/en-us/ef/core/dbcontext-configuration specifically the part where it mentions services.AddDbContext - Andy
Ive updated the configureservices ``` public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDbContext<ProductContext>( options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection")); }```, but still seem to get this error ystem.TypeLoadException: 'Method 'Create' in type 'Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerSqlTranslatingExpressionVisitorFactory' from assembly 'Microsoft.EntityFrameworkCore.SqlServer - ro_chl
i am assuming you didn't set up your connection string. - Andy

1 Answers

0
votes

Codes:

public void ConfigureServices(IServiceCollection services) {

services.AddControllersWithViews(); 
services.AddDbContext<ProductContext>( options => 
options.UseSqlServer("name=ConnectionStrings:DefaultConnection")); }

Connection string:

    "Logging": { 
    "LogLevel": 
    { 
"Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } 
}, 
    "AllowedHosts": "*", 
    "ConnectionStrings": { "productContext": "Server=(localdb)\\mssqllocaldb;Database=Products;Trusted_Connection=True;MultipleActiveResultSets=true" } }

According to your codes and connection strings, it seems that you used the productContext as the connection string name not DefaultConnection. I suggest you could try to modify the service as below and try again.

        services.AddDbContext<ProductContext>(options =>

            options.UseSqlServer(
                Configuration.GetConnectionString("productContext")));

If you don't inject the Configuration, you could try below:

  services.AddDbContext<ProductContext>( options => 
    options.UseSqlServer("name=ConnectionStrings:productContext"));