tobre
tobre

Reputation: 1405

Unable to resolve service for type 'System.Int32' while attempting to activate

In a ASP.NET Core 2.2 Razor Pages Web Site, I try to navigate from a list of bank account to the scaffolded edit page of a single bank account. The edit page does not open and the error message is displayed:

System.InvalidOperationException: Unable to resolve service for type 'System.Int32' while attempting to activate 'ForexWeb.Pages.BankAccountModel'. at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)

The bank accounts page (BankAccounts.cshtml) is

@page 
@model ForexWeb.Pages.BankAccountsModel

@{
    ViewData["Title"] = "BankAccounts";
    Layout = "~/Pages/Shared/_Layout.cshtml";
}

<h1>Bank Accounts</h1>

<table>
    @foreach (var account in Model.BankAccounts)
    {
        <tr>
            <td>@account.AccountNumber</td>
            <td>
                <a asp-page="Edit" asp-route-id="@account.Id">More</a>
                @*<a asp-action="Account/Edit" asp-route-id="@account.Id">Edit</a>*@
            </td>
        </tr>
    }
</table>

The edit page (Edit.cshtml) starts with

@page "{id}"
@model ForexWeb.Pages.BankAccountModel

@{
    ViewData["Title"] = "BankAccount";
    Layout = "~/Pages/Shared/_Layout.cshtml";
}

<h1>BankAccount</h1>

The routing is setup in the Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

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

    app.UseAuthentication();

    app.UseMvc(ConfigureRoutes);
}

private void ConfigureRoutes(IRouteBuilder routeBuilder)
{
    routeBuilder.MapRoute("Default", "{controller=Home}/action=Index/{id?}");
}

The BankAccountModel class

public class BankAccountModel : PageModel
{
    private readonly int _id;
    private readonly IForexRepository _repository;

    public BankAccountModel(int id, IForexRepository repository)
    {
        _id = id;
        _repository = repository;
    }

    [BindProperty]
    public ForexRepository.Entities.BankAccount BankAccount { get; set; }

    public async Task<IActionResult> OnGetAsync(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        BankAccount =  _repository.GetBankAccount((int)id);


        if (BankAccount == null)
        {
            return NotFound();
        }
        ViewData["BankId"] = new SelectList(_repository.GetBanks(), "Id", "Id");
        return Page();
    }

    public IActionResult OnGet()
    {
        var bankAccount = _repository.GetBankAccount(_id);
        BankAccount = bankAccount;
        return Page();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _repository.AddBankAccount(BankAccount.BankId,BankAccount);

        try
        {
            _repository.Save();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!BankAccountExists(BankAccount.Id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return RedirectToPage("./Index");
    }

    private bool BankAccountExists(int id)
    {
        return _repository.GetBankAccount(id) != null;
    }
}

What could be the issue?

Upvotes: 2

Views: 3510

Answers (1)

Alexander
Alexander

Reputation: 9632

The BankAccountModel is created by DI container. While creating page model the container is resolving all constructor parameters in order to inject them and create an instance of BankAccountModel. An exception is thrown when the container tries to resolve service of type int which apparently is not registered. So you need to remove int parameter from the constructor

public BankAccountModel(IForexRepository repository)
{
    _repository = repository;
}

Upvotes: 6

Related Questions