我正在尝试为Entity Framework实现存储库解决方案,但是我在使用Unity注册包含泛型的类型时遇到了问题.
鉴于:
// IRepository interface
public interface IRepository<TEntity>
{
// omitted for brevity
}
// Repository implementation
public class Repository<TEntity, TContext> : IRepository<TEntity>, IDisposable
where TEntity : class
where TContext : DbContext
{
// omitted for brevity
}
// service layer constructor
public MyServiceConstructor(IRepository<Account> repository)
{
_repository = repository;
}
Run Code Online (Sandbox Code Playgroud)
我需要将IRepository的类型映射注册到Repository.但是我在使用这种映射的Unity语法时遇到了麻烦.
我试过以下没有运气:
container.RegisterType<IRepository<>, typeof(Repository<,>)>();
container.RegisterType<typeof(IRepository<>), Repository<,>>();
Run Code Online (Sandbox Code Playgroud)
编辑
基于@Steven响应我现在有以下实现:
// UnityRepository implementation
public class UnityRepository<TEntity> : Repository<TEntity, MyDbContextEntities>
where TEntity : class
{
public UnityRepository() : …Run Code Online (Sandbox Code Playgroud) entity-framework unity-container separation-of-concerns repository-pattern