Invalidoperationexception: Unable to resolve service for type while attempting to Activate

Asked

Viewed 14 times

0

This is probably a duplicate question, but all the questions I saw didn’t solve the problem.

The mistake happening is:

Erro ao tentar fazer um Dependency injection

The flow is as follows: View -> Controller -> Service -> Repository

Dependency Injection is not working for the service applied to Scoped in the file Statup.Cs.

public void ConfigureServices(IServiceCollection services)
    {

        var connection = Configuration["SqlConnection:SqlConnectionString"];
        services.AddDbContext<AimbraDocContext>(options => options.UseSqlServer(connection));

        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddScoped<IUserService, UserServiceImpl>();
        services.AddScoped<IUserRepository, UserRepositoryImpl>();
        services.AddScoped(
            typeof(IRepository<>),
            typeof(GenericRepository<>)
            );


        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

The problem is happening with Userservice, where I have the following interface and implementation:

public interface IUserService
    {
        UserVM Create(UserVM user);

        List<UserVM> FindAll();

        UserVM FindbyUsername(string username);

        UserVM FindbyEmail(string email);

        UserVM FindById(int id);

        UserVM Update(UserVM user);

        void Delete(int id);
    }

public class UserServiceImpl : IUserService
    {

        private readonly UserConverter _converter;
        private readonly IUserRepository _repository;

        public UserServiceImpl(UserConverter converter, IUserRepository repository)
        {
            _repository = repository;
            _converter = new UserConverter();
        }

        public UserVM Create(UserVM user)
        {
            var userEntity = _converter.Parse(user);
            userEntity.CreatedAt = new DateTime();
            userEntity.UpdatedAt = new DateTime();
            userEntity.Token = Guid.NewGuid().ToString("N").Substring(0, 5);
            userEntity.TokenCreatedAt = new DateTime();

            userEntity = _repository.Create(userEntity);

            return _converter.Parse(userEntity);
        }

        public void Delete(int id)
        {
            _repository.Delete(id);
        }

        public List<UserVM> FindAll()
        {
            return _converter.ParseList(_repository.FindAll());
        }

        public UserVM FindbyEmail(string email)
        {
            return _converter.Parse(_repository.FindByEmail(email));
        }

        public UserVM FindById(int id)
        {
            return _converter.Parse(_repository.FindById(id));
        }

        public UserVM FindbyUsername(string username)
        {
            return _converter.Parse(_repository.FindByUsername(username));
        }

        public UserVM Update(UserVM user)
        {
            var userEntity = _converter.Parse(user);
            userEntity.UpdatedAt = new DateTime();
            userEntity = _repository.Update(userEntity);
            return _converter.Parse(userEntity);
        }
    }

My View:

@model AimbraDocMVC.Data.VM.UserVM

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<h4>UserVM</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Index">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Username" class="control-label"></label>
                <input asp-for="Username" class="form-control" />
                <span asp-validation-for="Username" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Password" class="control-label"></label>
                <input asp-for="Password" class="form-control" />
                <span asp-validation-for="Password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="PasswordConfirm" class="control-label"></label>
                <input asp-for="PasswordConfirm" class="form-control" />
                <span asp-validation-for="PasswordConfirm" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

The implementation of the Userrepository:

public class UserRepositoryImpl : GenericRepository<User>, IUserRepository
    {   
        public UserRepositoryImpl(AimbraDocContext context) : base(context)
        {
        }

        public User FindByEmail(string email)
        {
            if (email == null) return null;
            var result  = _context.Users.SingleOrDefault(u => u.Email.Equals(email));
            if (result == null) return null;
            return result;
        }

        public User FindByUsername(string username)
        {
            if (username == null) return null;
            var result = _context.Users.SingleOrDefault(u => u.Username.Equals(username));
            if (result == null) return null;
            return result;
        }
    }
  • I’ve seen this post, and if you read my Francisco, you’ll see that I implemented it in the format shown and even then the problem is generated.

  • 1

    The problem is the same, you are asking for an instance of UserConverter without having added it to the services.

  • This service is at Startup.Cs?

  • Truth... I understood the error. I was declaring the convert in the builder, which in fact was only instantiating.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.