Ошибка в ASP Net MVC: InvalidOperationException: невозможно разрешить службу для типа - PullRequest
0 голосов
/ 20 июня 2019

Я пытаюсь добавить продукт в базу данных в 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

...