简体   繁体   中英

No service for type T has been registered WebApi 3.1

Trying to inject in my controller a repo but it's not working and I keep getting the same error. This is how I'm doing.

The Interface

public interface IGeneral
{
    Task<Message> RegisterAsync(UserModel model);
}

The Context

public abstract class BaseRepository
{
    protected readonly Context Context;

    public BaseRepository(Context context)
    {
        Context = context;
    }
}

Repository

public class General : BaseRepository, IGeneral
{
    public General(Context context) : base(context) {}

    public async Task<Message> RegisterAsync(UserModel model)
    {
        var result = await Context.User.Where(a => a.Email == model.Email).FirstOrDefaultAsync();
        if(result != null)
        {
            await Context.User.AddAsync(new Data.Access.Models.User 
            { Date = DateTime.Now, Email = model.Email, Name = model.Name, Password = model.Password });
            await Context.SaveChangesAsync();
        }
        return Message.Exists;
    }
}

The Implementation

[HttpPost("Register")]
    public async Task<IActionResult> Register([FromServices] General general, UserModel userModel)
    {
        try
        {
            return Ok(await general.RegisterAsync(userModel));
        }
        catch (Exception ex)
        {
            return BadRequest();
        }
    }

Startup.cs

services.AddTransient<IGeneral, General>();

And the Exeption that I get from Postman!

System.InvalidOperationException: No service for type 'Mangue.Api.Services.Repository.General' has been registered. at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ServicesModelBinder.BindModelAsync(ModelBindingContext bindingContext) at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value) at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<g__Bind|0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

You register a service of type IGeneral (which resolves to General ) but you request an instance of General instead of IGeneral .
Change General to IGeneral in the Register function and it'll work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM