简体   繁体   中英

How to inject multiple dependencies (each inside of other?) - .Net Core 3.1

So.. It may sound kinda stupid, but here I go... I'm currently working on a project that has the following structure

Project Structure

So I got the Services, Controllers, Repositories and Models...

Here's the Controller, which I'm trying to instantiate the Services Class.


namespace WebApi.Controllers
{
    [Route("api/usuarios")]
    [ApiController]
    public class UsuariosController : ControllerBase
    {
        private readonly IUsuariosService _service;

        public UsuariosController(IUsuariosService service)
        {
            _service = service;
            
        }

        

        // private readonly MockUsuarioRepo _repository = new MockUsuarioRepo();
        // GET: api/<ValuesController>
        [HttpGet]
        public ActionResult <IEnumerable<Usuarios>> Get()
        {
            var usuariosList = _service.GetAllUsuarios();

            return Ok(usuariosList);
        }
        
        [HttpGet]
        [Route("authenticated")]
        [Authorize]
        public string Authenticated() => String.Format("Autenticado - {0}", User.Identity.Name);

        // POST api/<ValuesController>
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/<ValuesController>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/<ValuesController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

Which by is trying to instantiate the Repositories


namespace Application.Services
{
    public class UsuariosService : IUsuariosService
    {
        private readonly UsuariosRepo _repository;
        public UsuariosService(UsuariosRepo repository) {
            _repository = repository;
        }
        public IEnumerable<Usuarios> GetAllUsuarios()
        {
            return _repository.GetUsuarios();
        }
        public static string GenerateToken(Usuarios usuario)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(Settings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, usuario.Nome.ToString()),
                    new Claim(ClaimTypes.Email, usuario.Email.ToString()),
                }),
                Expires = DateTime.UtcNow.AddHours(2),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature
                )
                
            };
            tokenHandler.CreateToken(tokenDescriptor);
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);

        }

        public Usuarios DoLogin(string username, string password, string name)
        {
            throw new NotImplementedException();
        }
    }
}

Well, I learned how to instantiate the Repos, by using in the following method on Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {
            ...
            services.AddControllers();
            services.AddScoped<IUsuariosRepo, UsuariosRepo>();
            ...

But I think that the services is not instantiate at all. That's the error given when I make a GET request to "usuarios"

Unable to resolve service for type 'Application.Services.Interfaces.IUsuariosService' while attempting to activate 'WebApi.Controllers.UsuariosController'.

Any thoughts? Thanks in advance.

First thing that is wrong in your code is that you did not inject IUsuariosService in ConfigureServices:

services.AddScoped<IUsuariosService, UsuariosService>();

and the second point you have to care about is that, you did not use the interface in your service layer, base on Dependency Inversion Principle classes should depend upon interfaces so we have to use interfaces instead of UsuariosRepo class.

    private readonly IUsuariosRepo _repository;
    public UsuariosService(IUsuariosRepo repository)
    {
          _repository = repository;
    }

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