我有一个通用的仓库架构,看起来像这样:
仓库
然后,具体的实现就像这样创建:
用户存储库(UserRepository)
我可能会有很多服务,所以不想将每个服务单独传递到控制器中,我想尝试传递一个可以为我生成存储库的单个工厂。 RepositoryFactory
现在,在设置依赖注入时,我像这样注册了服务:
Startup.cs
这是在控制器中使用的全部内容,如下所示:
控制器
当我在`repositoryFactory.GetRepository()`方法中调用`_provider.GetRequiredService()`时,我会得到上面注释中的错误。
`RepositoryFactory`正常传递,但是`UserRepository`没有被注册。我错过了什么?我尝试在构造函数之外调用`GetRepository`方法,并尝试将`AddScoped`更改为其他`Add`变体(如`Transient`和`Singleton`),但都没有成功。
仓库
public interface IRepository<T> where T: class
{
IList<T> Get(Func<T, bool> where);
}
public abstract class Repository<T> : IRepository<T> where T: class
{
private readonly DbSet<T> _entity;
protected Repository(ApplicationDbContext dbContext)
{
_entity = dbContext.Set<T>();
}
public IList<T> Get(Func<T, bool> where)
{
return _entity.Where(where).ToList();
}
}
然后,具体的实现就像这样创建:
用户存储库(UserRepository)
public class UserRepository : Repository<ApplicationUser>
{
public UserRepository(ApplicationDbContext dbContext) : base(dbContext) {}
// Can add any other methods I want that aren't included in IRepository
}
我可能会有很多服务,所以不想将每个服务单独传递到控制器中,我想尝试传递一个可以为我生成存储库的单个工厂。 RepositoryFactory
public interface IRepositoryFactory
{
T GetRepository<T>() where T : class;
}
public class RepositoryFactory : IRepositoryFactory
{
private readonly IServiceProvider _provider;
public RepositoryFactory(IServiceProvider serviceProvider)
{
_provider = serviceProvider;
}
public T GetRepository<T>() where T : class
{
return _provider.GetRequiredService<T>(); // ERROR: No service for type 'UserRepository' has been registered
}
}
现在,在设置依赖注入时,我像这样注册了服务:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// [...]
services.AddScoped<IRepository<ApplicationUser>, UserRepository>();
services.AddScoped<IRepositoryFactory, RepositoryFactory>();
// [...]
}
这是在控制器中使用的全部内容,如下所示:
控制器
public class HomeController : Controller
{
private readonly UserRepository _userRepository;
public HomeController(IRepositoryFactory repositoryFactory)
{
_userRepository = repositoryFactory.GetRepository<UserRepository>(); // ERROR: No service for type 'UserRepository' has been registered
}
// [...]
}
当我在`repositoryFactory.GetRepository()`方法中调用`_provider.GetRequiredService()`时,我会得到上面注释中的错误。
`RepositoryFactory`正常传递,但是`UserRepository`没有被注册。我错过了什么?我尝试在构造函数之外调用`GetRepository`方法,并尝试将`AddScoped`更改为其他`Add`变体(如`Transient`和`Singleton`),但都没有成功。
.cshtml
视图中,我实现了@inject MyService
,但我应该使用@inject IMyService
接口。 - Bob Kaufman