Search code examples
c#dependency-injectionaspnetboilerplate

How ABP generate IRepository<TEntity> for Entity


I am trying to understand how ABP does the above.

The normal workflow in ABP is:

  1. Add the entity class inheriting from Entity based class to the Core project
  2. Add the DbSet to the context in EFCore project
  3. Add a new IEntityAppService interface and implementation to Application project
  4. In the IEntityAppService implementation inject the IRepository to the constructor
  5. Enjoy!!

What I have done to try to understand:

  1. I have looked at the Abp source code and got the impression that this is being done by Open Generics between IRepository<T> and EfCoreRepositoryBase<T> with Factory magic. However, I tried to do this in AspNetCore DI with:

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        // adding DbContext
        // adding Mvc etc....
    
        // RepositoryBase => like EfCoreRepositoryBase in ABP
        // Error on this line, DI can not instantiate RepositoryBase as it is abstract
        services.AddTransient<IRepository<>, RepositoryBase<>);
    }
    

Please can someone explain the mechanism to me?


Solution

  • The magic is in EfGenericRepositoryRegistrar.cs where:

    foreach (var entityTypeInfo in _dbContextEntityFinder.GetEntityTypeInfos(dbContextType))
    {
        // ...
    
        iocManager.IocContainer.Register(
            Component
                .For(genericRepositoryType)
                .ImplementedBy(implType)
                .Named(Guid.NewGuid().ToString("N"))
                .LifestyleTransient()
    }
    

    Note that EfCoreRepositoryBaseOfTEntityAndTPrimaryKey.cs is not abstract.