ASP Net MVC中的错误:InvalidOperationException:无法解析类型的服务

时间:2019-06-20 01:28:34

标签: c# asp.net-core dependency-injection asp.net-core-mvc

我正在尝试将产品添加到ASP Net MVC中的数据库。我相信我已经正确设置了所有内容,进行了DependencyInjection等。但是我无法运行我的代码。

我在startup.cs中添加了依赖项注入,并且代码中的任何地方都没有错误。

ProductController.cs

 public class ProductController : Controller
{
    private readonly ProjContext context;
    private readonly IAddProductCommand _addProduct;

    public ProductController(ProjContext context, IAddProductCommand addProduct)
    {
        this.context = context;
        _addProduct = addProduct;
    }



    // GET: Product
    public ActionResult Index()
    {
        var lista = new List<ProductDTO>{new ProductDTO {
            Id = 1,
            ProductName = "Iphone",
            SupplierId = 1,
            UnitPrice = 555,
            Package = "DHL",
            IsDiscontinued = false
        },new ProductDTO{
              Id = 2,
            ProductName = "Nokia",
            SupplierId = 3,
            UnitPrice = 456,
            Package = "Express",
            IsDiscontinued = true
        }

        };
        return View(lista);
    }

    // GET: Product/Details/5
    public ActionResult Details(int id)
    {
        return View();
    }

    // GET: Product/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Product/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(ProductDTO dto)
    {

        if (!ModelState.IsValid) {
            return View(dto);
        }
        try
        {
            // TODO: Add insert logic here
            _addProduct.Execute(dto);
            return RedirectToAction(nameof(Index));
        }
        catch (EntityAlreadyExistsException)
        {
            TempData["error"] = "Produkt vec postoji.";
        }
        catch (Exception) {
            TempData["error"] = "Doslo je do greske.";

        }
        return View();
    }

    // GET: Product/Edit/5
    public ActionResult Edit(int id)
    {
        return View();
    }

    // POST: Product/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(int id, IFormCollection collection)
    {
        try
        {
            // TODO: Add update logic here

            return RedirectToAction(nameof(Index));
        }
        catch
        {
            return View();
        }
    }

    // GET: Product/Delete/5


    // POST: Product/Delete/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Delete(int id, IFormCollection collection)
    {
        try
        {
            // TODO: Add delete logic here

            return RedirectToAction(nameof(Index));
        }
        catch
        {
            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.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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddDbContext<ProjContext>();
        services.AddTransient<IAddProductCommand,EfAddProductCommand>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

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

IAddProductCommand

public interface IAddProductCommand : ICommand<ProductDTO>
{
}

EfAddProductCommand

public class EfAddProductCommand :IAddProductCommand
{

    private readonly ProjContext _context;

    public EfAddProductCommand(ProjContext context)
    {
        _context = context;
    }

    public void Execute(ProductDTO request) {

        if (_context.Product.Any(p => p.ProductName == request.ProductName)) {
            throw new EntityAlreadyExistsException();
        }

        _context.Product.Add(new Product {
            ProductName=request.ProductName,
            SupplierId = request.SupplierId,
            UnitPrice = request.UnitPrice,
            Package = request.Package,
            IsDiscontinued = request.IsDiscontinued
        });
        _context.SaveChanges();
    }


}

这是我得到的错误: http://prntscr.com/o454oa

0 个答案:

没有答案