【发布时间】:2018-07-07 20:44:02
【问题描述】:
我创建了一个 .NET Core 2.0 MVC 应用程序并使用依赖注入和存储库模式将存储库注入我的控制器。不过,我是 当我的 UserService 将要注入 UserController 时出现错误:
InvalidOperationException:尝试激活“FFLEX.Services.User.UserService”时无法解析“FFLEX.Services.Repository.IGenericRepository`1[FFLEX.Core.ApplicationUser]”类型的服务。
GenericRepository
public class GenericRepository<T> : IGenericRepository<T> where T : class {
protected ApplicationDbContext _context;
public GenericRepository(ApplicationDbContext context) {
_context = context;
}
public IQueryable<T> GetAll() {
return _context.Set<T>();
}
public virtual async Task<ICollection<T>> GetAllAsyn() {
return await _context.Set<T>().ToListAsync();
}
}
IUserService
public interface IUserService {
Task<ICollection<ApplicationUser>> GetAllNonSuperAdminUsers();
}
用户服务
public class UserService : IUserService {
protected readonly IGenericRepository<ApplicationUser> _repository;
public UserService(IGenericRepository<ApplicationUser> repository) {
repository = repository;
}
public async Task<ICollection<ApplicationUser>> GetAllNonSuperAdminUsers() {
return await _repository.GetAllAsyn();
}
}
用户控制器
public class UserController : Controller {
private readonly IUserService _userService;
public UserController(IUserService userService) {
userService = userService;
}
public async Task<IActionResult> Index() {
var test = await PrepareUserViewModel();
return View(test);
}
public async Task<UserViewModel> PrepareUserViewModel() {
UserViewModel vm = new UserViewModel();
vm.UserCount = 1;
vm.Subscribers = 1;
vm.Guest = 1;
vm.Users = await _userService.GetAllNonSuperAdminUsers();
return vm;
}
}
Startup.cs 配置
public void ConfigureServices(IServiceCollection services) {
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(FFLEXConsts.ConnectionString));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
//services.AddTransient<IUserService, UserService>();
services.AddScoped<IUserService, UserService>();
services.AddMvc();
}
我不确定我做错了什么。请帮我解决这个问题,因为它似乎没有任何问题。
【问题讨论】:
-
我没有看到您注册
IGenericRepository<ApplicationUser>,从错误看来注射器无法解决它。你有什么理由不在ConfigureServices方法中注册它? -
您的
ConfigureServices方法中缺少services.AddScoped<IGenericRepository<ApplicationUser>, GenericRepository<ApplicationUser>>();。 -
@CalC 非常感谢它的工作:)
标签: c# asp.net dependency-injection asp.net-identity asp.net-core-mvc-2.0