Hi,
I have created a generic repository to write common method for all repositories. but it is not working for me. what i have done is, created IGenericRepository under core and implemented IRepository then created GenericRepository under EnitityFramework and implemented SampleProBaseRepository as well as IGenericRepository(Codes are bellow).
This is not working for me, please cross check the code and let me know if there any mistake i did or i should add some more code to the work the same.
IGenericRepository:
public interface IGenericRepository<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey> where TEntity : class,IEntity<TPrimaryKey>
{
Task SaveChangesAsync();
}
public interface IGenericRepository<TEntity> : IRepository<TEntity> where TEntity : class,IEntity<int>
{
Task SaveChangesAsync();
}
GenericRepository
public class GenericRepository<TEntity, PrimaryKey> : SampleRepositoryBase<TEntity, PrimaryKey>, IGenericRepository<TEntity, PrimaryKey> where TEntity : class,IEntity<PrimaryKey>
{
protected GenericRepository(IDbContextProvider<SampleDbContext> dbContextProvider)
: base(dbContextProvider)
{
}
public async Task SaveChangesAsync()
{
await Context.SaveChangesAsync();
}
}
public class GenericRepository<TEntity> : SampleRepositoryBase<TEntity>, IGenericRepository<TEntity> where TEntity : class,IEntity<int>
{
protected GenericRepository(IDbContextProvider<SampleDbContext> dbContextProvider)
: base(dbContextProvider)
{
}
public async Task SaveChangesAsync()
{
await Context.SaveChangesAsync();
}
}
6 Answer(s)
-
0
You should register your generic repository to DI to be able to inject it.
For example, you can register it like that in PreInitialize of your module:
IocManager.IocContainer.Register( Component.For<IGenericRepository<>>().ImplementedBy<GenericRepository<>>().LifeStyleTransient() );
This make possible to inject IGenericRepository<MyEntity> for example. You should do similar for also GenericRepository<TEntity, PrimaryKey>
-
0
But I have tried register Generic Repository like follows,
IocManager.Register(typeof(IGenericRepository<>), typeof(GenericRepository<>), Abp.Dependency.DependencyLifeStyle.Transient);
this been resulted the same.
-
0
Hi,
I have tried register generic repository the way you mentioned. but it showing some build error like "using the generic type 'Sample.Repository.GenericRepository<TEntity>' requires 1 type argument" . so are gonna say i must me register all entity separately at preinitialize..?
-
0
Hi,
Can you try to register it like this ?
IocManager.Register(typeof(IGenericRepository<>), typeof(GenericRepository<,>), Abp.Dependency.DependencyLifeStyle.Transient);
-
0
where should i intialize in repository??
IocManager.Register(typeof(IGenericRepository<>), typeof(GenericRepository<,>), Abp.Dependency.DependencyLifeStyle.Transient);
-
0
Hi,
You need to put this code in PreInitialize method of your module.