Szpisjak Cristian Szpisjak Cristian - 1 month ago 16
C# Question

ASP.NET Core services registration error

I have the following class in a project Models:

public interface IUserService
{
IEnumerable<ApplicationUser> GetUsers(string FirstName = null);
ApplicationUser GetUserById(string Id);
ApplicationUser GetUserByUsername(string Username);
void CreateUser(ApplicationUser User);
void SaveUser();
}

public class UserService : IUserService
{
private readonly IUserRepository usersRepository;
private readonly IUnitOfWork unitOfWork;

public UserService(IUserRepository usersRepository, IUnitOfWork unitOfWork)
{
this.usersRepository = usersRepository;
this.unitOfWork = unitOfWork;
}

#region Members

public void CreateUser(ApplicationUser User)
{
throw new NotImplementedException();
}

public ApplicationUser GetUserById(string Id)
{
var user = usersRepository.GetUserById(Id);
return user;
}

public ApplicationUser GetUserByUsername(string Username)
{
var user = usersRepository.GetUserByUsername(Username);
return user;
}

public IEnumerable<ApplicationUser> GetUsers(string FirstName = null)
{
if (string.IsNullOrEmpty(FirstName))
{
return usersRepository.GetAll();
}
return usersRepository.GetAll()
.Where(c => c.Profile.FirstName == FirstName);
}

public void SaveUser()
{
unitOfWork.Commit();
}

#endregion
}


On my ASP.NET Core (Full .NET Framework), in Startup.cs i have:

// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddScoped<IUserService, UserService>();


I get an error when i run the application:

InvalidOperationException: Unable to resolve service for type 'Data.Repositories.Identity.IUserRepository' while attempting to activate 'Service.Identity.UserService'.


Like i said upper, this is an ASP.NET Core with Full .NET Framework. Any thoughts?

Answer

You have to register everything in your services collection what you want to be injected in your classes constructors. As far as I can ses:

public UserService(IUserRepository usersRepository, IUnitOfWork unitOfWork)
{
    this.usersRepository = usersRepository;
    this.unitOfWork = unitOfWork;
}

you expect that IUserRepository and IUnitOfWork will be automatically resolved and injected - so they have to be registered to. If UnitOfWork requires IDbFactory in the constructor to be injected then it also have to be registered in the service collection. Otherwise Dependency Injection framework won't known to to resolve it.

Comments