1 votes

ASP.NET Core 2.2 Multiple constructors accepting all given argument types have been found in type 'MoviesController'

I have a problem that I don't quite understand and I don't know how to solve.

I'm learning how to use ASP.NET Core with Microsoft tutorials, looking at other sites to learn how to globalize and internationalize an application, etc... and sometimes I get quite lost...

When I run the web, it works without problems, but when I click on the link to go to another method, I get this error:

An unhandled exception occurred while processing the request. InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'MvcMovie.Controllers.MoviesController'. There should only be one applicable constructor. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.TryFindMatchingConstructor(Type instanceType, Type[] argumentTypes, ref ConstructorInfo matchingConstructor, ref Nullable[] parameterMap)

It seems to be a problem of drivers and such, but I don't understand why.

This is the controller that seems to fail:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using MvcMovie.Models;

namespace MvcMovie.Controllers
{
    public class MoviesController : Controller
 {
    private readonly IStringLocalizer<MoviesController> _localizer;

    public MoviesController(IStringLocalizer<MoviesController> localizer)
    {
        _localizer = localizer;
    }

    private readonly MvcMovieContext _context;

    public MoviesController(MvcMovieContext context)
    {
        _context = context;
    }

    // GET: Movies
    public async Task<IActionResult> Index(string movieGenre, string searchString)
    {
        //ViewData["controllerText"] = _localizer["Texto de ejemplo pasado desde el controlador."];

        // Use LINQ to get list of genres.
        IQueryable<string> genreQuery = from m in _context.Movie
                                        orderby m.Genre
                                        select m.Genre;

        var movies = from m in _context.Movie
                     select m;

        if (!string.IsNullOrEmpty(searchString))
        {
            movies = movies.Where(s => s.Title.Contains(searchString));
        }

        if (!string.IsNullOrEmpty(movieGenre))
        {
            movies = movies.Where(x => x.Genre == movieGenre);
        }

        var movieGenreVM = new MovieGenreViewModel
        {
            Genres = new SelectList(await genreQuery.Distinct().ToListAsync()),
            Movies = await movies.ToListAsync()
        };

        return View(movieGenreVM);
    }

    // GET: Movies/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var movie = await _context.Movie
            .FirstOrDefaultAsync(m => m.Id == id);
        if (movie == null)
        {
            return NotFound();
        }

        return View(movie);
    }

    // GET: Movies/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: Movies/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price,Rating")] Movie movie)
    {
        if (ModelState.IsValid)
        {
            _context.Add(movie);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(movie);
    }

    // GET: Movies/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var movie = await _context.Movie.FindAsync(id);
        if (movie == null)
        {
            return NotFound();
        }
        return View(movie);
    }

    // POST: Movies/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,Title,ReleaseDate,Genre,Price,Rating")] Movie movie)
    {
        if (id != movie.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(movie);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MovieExists(movie.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(movie);
    }

    // GET: Movies/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var movie = await _context.Movie
            .FirstOrDefaultAsync(m => m.Id == id);
        if (movie == null)
        {
            return NotFound();
        }

        return View(movie);
    }

    // POST: Movies/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var movie = await _context.Movie.FindAsync(id);
        _context.Movie.Remove(movie);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool MovieExists(int id)
    {
        return _context.Movie.Any(e => e.Id == id);
    }

    public IActionResult SetLanguage(string culture, string returnUrl)
    {
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
            new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) 
    }
        );

        return LocalRedirect(returnUrl);
    }
   }
  }

Let's see if you can give me some clue, please. I put an access to my git in case you want to take a look:

https://github.com/erniker/TrainingNETCore/tree/master/MvcMovie

Thank you in advance!

0 votes

I understand that in this type of injections you cannot have several constructors. You must leave only one.

1voto

Rafael Acosta Points 1

In your Controller, you are receiving via Dependency Injection through the Constructor the objects localizer y context .

In these cases where a Dependency Injection is performed, you are only allowed to define one sole Constructor . This is because if you define multiple Constructors, you would not be able to determine which of them is the one that should be used. initialize the Controlling Class.

You must define a single Builder as follows:

private readonly MvcMovieContext _context;
private readonly IStringLocalizer<MoviesController> _localizer;

public MoviesController(IStringLocalizer<MoviesController> localizer, MvcMovieContext context)
{
    _localizer = localizer;
    _context = context;
}

0 votes

Thank you very much Rafael, I had also seen this in another thread here, but I didn't know how to apply the solution, now everything is going great :)

0 votes

@JoséPabloMedinaGrande: Great! Remember to always value the answers that have helped you to solve your question, with that you will be collaborating with the good health of this site.

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X