ASP.. NET核心服务注册错误
本文关键字:注册 错误 服务 核心 NET ASP | 更新日期: 2023-09-27 18:14:08
我在一个项目模型中有以下类:
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
}
在我的ASP。.NET Core (Full .NET Framework),在Startup.cs中我有:
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddScoped<IUserService, UserService>();
我得到一个错误,当我运行应用程序:
InvalidOperationException: Unable to resolve service for type 'Data.Repositories.Identity.IUserRepository' while attempting to activate 'Service.Identity.UserService'.
就像我上面说的,这是一个ASP。.NET Core和完整的。NET框架。任何想法吗?
你必须在你的服务集合中注册所有你想要注入到你的类构造函数中的东西。据我所知:
public UserService(IUserRepository usersRepository, IUnitOfWork unitOfWork)
{
this.usersRepository = usersRepository;
this.unitOfWork = unitOfWork;
}
你期望IUserRepository和IUnitOfWork将被自动解析和注入——所以它们必须被注册到。如果UnitOfWork需要在构造函数中注入IDbFactory,那么它也必须在服务集合中注册。