Home > OS >  .NET 6 ... unable to resolve service for type
.NET 6 ... unable to resolve service for type

Time:03-04

I'm using NuGet packages in VS 2022:

Microsoft.EntityFrameworkCore.SQLServer Microsoft.EntityFrameworkCore.Tools

Connected to my SQL server (all good), all my models partial classes generated. I add a new controller (Add New Scaffolded Item) and select "MVC Controller with views, using Entity Framework". Select my Model class "Phonenumbertype" my Data context class "JMSContext" (just web API no front end tested thru Swagger). My controller gets generated

namespace WebAppTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PhonenumbertypesController : ControllerBase
    {

    // Error out with code generated:
    // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/startup?view=aspnetcore-6.0
    // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-6.0

    // Possible Solution
    // https://stackoverflow.com/questions/40900414/asp-net-core-dependency-injection-error-unable-to-resolve-service-for-type-whil

    private readonly JMSContext _context;

    public PhonenumbertypesController(JMSContext context)
    {
        _context = context;
    }

    // GET: api/Phonenumbertypes
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Phonenumbertype>>> GetPhonenumbertypes()
    {
        return await _context.Phonenumbertypes.ToListAsync();
    }

    // GET: api/Phonenumbertypes/5
    [HttpGet("{id}")]
    public async Task<ActionResult<Phonenumbertype>> GetPhonenumbertype(short id)
    {
        var phonenumbertype = await _context.Phonenumbertypes.FindAsync(id);

        if (phonenumbertype == null)
        {
            return NotFound();
        }

        return phonenumbertype;
    }

    // PUT: api/Phonenumbertypes/5
    // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
    [HttpPut("{id}")]
    public async Task<IActionResult> PutPhonenumbertype(short id, Phonenumbertype phonenumbertype)
    {
        if (id != phonenumbertype.PhtId)
        {
            return BadRequest();
        }

        _context.Entry(phonenumbertype).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!PhonenumbertypeExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    // POST: api/Phonenumbertypes
    // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
    [HttpPost]
    public async Task<ActionResult<Phonenumbertype>> PostPhonenumbertype(Phonenumbertype phonenumbertype)
    {
        _context.Phonenumbertypes.Add(phonenumbertype);
        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (PhonenumbertypeExists(phonenumbertype.PhtId))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtAction("GetPhonenumbertype", new { id = phonenumbertype.PhtId }, phonenumbertype);
    }

    // DELETE: api/Phonenumbertypes/5
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeletePhonenumbertype(short id)
    {
        var phonenumbertype = await _context.Phonenumbertypes.FindAsync(id);
        if (phonenumbertype == null)
        {
            return NotFound();
        }

        _context.Phonenumbertypes.Remove(phonenumbertype);
        await _context.SaveChangesAsync();

        return NoContent();
    }

    private bool PhonenumbertypeExists(short id)
    {
        return _context.Phonenumbertypes.Any(e => e.PhtId == id);
    }
   }
}

I run my web API, Swagger starts, select my API (Try Out) and get Error: response status is 500 and the following body:

System.InvalidOperationException: Unable to resolve service for type 'WebAppTest.Models.JMSContext' while attempting to activate 'WebAppTest.Controllers.PhonenumbertypesController'. at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired) at lambda_method9(Closure , IServiceProvider , Object[] )....

This is all auto-generated code so my expectations was that is would work and I would expand my code from there ... this is just a basic test.

It was able to get the results I wanted by removing all the auto-generated code in controller class ... BUT, I'm trying to figure out why the auto-generated code doesn't work?

CodePudding user response:

Auto generated code assumes you have setup dependency registration already. In your case you have not added JMSContext to the dependency container.

You need to add JMSContext to the DI

If you are using Startup file, then you can do

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<JMSContext>(options => options.UseSqlServer(Configuration.GetConnectionString("YourConnectionStringKeyName_From_AppSettings.json"));
    //----- rest of the code
}

and if you are not using Startup file, then in your Program.cs file, before building the app, you can use

builder.Services.AddDbContext<JMSContext>(options => options.UseSqlServer(Configuration.GetConnectionString("YourConnectionStringKeyName_From_AppSettings.json"));

CodePudding user response:

You need to resovle the JMSContext class in the startup.cs class like this. More on Dependency injection in .NET

  • Related