EF Core,数据库优先。如何将通用存储库接口移至另一个程序集?

Lea*_*ner 8 c# repository-pattern ef-database-first entity-framework-core asp.net-core

我使用本教程来创建数据库模型

I decided to create another assembly for abstractions such as IRepository, IFooService by reading this quote of "Programming .NET Components" by Juwal Lowy:

Because interfaces can be implemented by multiple components, it's good practice to put them in a separate assembly from that of the implementing components.

My solution structure could look like this:

PersonsApp.Solution
--PersonsApp.WebUI
   -- Controllers (PersonController)
--PersonApp.Common
   --Core folder
      -IGenericRepository.cs (Abstraction)
      -IUnitOfWork.cs (Abstraction)  
   --Repositories folder
      -IPersonRepository.cs (Abstraction)
--PersonApp.Persistence  
  --Infrastructure folder
      -DbDactory.cs (Implementation)
      -Disposable.cs (Implementation)
      -IDbFactory.cs (Abstraction)
      -RepositoryBase.cs (Abstraction)
  --Models folder(Here we have DbContext, EF models (Implementation))      
      -Person.cs (Implementation)
      -PersonContext.cs (Implementation)
  --Repositories folder
      -PersonRepository.cs (Implementation)
Run Code Online (Sandbox Code Playgroud)

However, PersonApp.Persistence project has a reference to PersonApp.Common. But my project PersonApp.Common also needs a reference to PersonApp.Persistence because I would like to create a IPersonRepository.cs in Person.Common:

public interface IPersonRepository : IRepository<Person> {}
Run Code Online (Sandbox Code Playgroud)

The following error is thrown, when I try to add a reference to PersonApp.Persistence into PersonApp.Common:

A reference to 'PersonApp.Persistence' could not be added. Adding this project as a reference would cause a circular dependency.

但是,我真的很想为接口提供单独的程序集,为实体框架提供另一个程序集。

如何将存储库接口移至另一个部件?

另外,我希望将来能够通过保留data来使数据库架构与EF Core模型保持同步

我使用DatabaseFirst。预先感谢。任何帮助将不胜感激!

Ton*_*Ngo 0

这是我应用通用存储库的方法。

我定义了 1 个接口和 1 个类,其结构如下

public interface IGenericRepository<T> where T : class

public class GenericRepository<T> : IGenericRepository<T> where T : class
Run Code Online (Sandbox Code Playgroud)

您可以查看完整代码

IGenericRepository.cs

通用存储库.cs

任何我的博客

然后我可以这样注册

services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
Run Code Online (Sandbox Code Playgroud)

如果您想在类库中使用,您必须实现 IServiceCollection 接口,然后在 Startup.cs 中注册如下所示

public static IServiceCollection InjectApplicationServices(this IServiceCollection services)
{
    services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
}
Run Code Online (Sandbox Code Playgroud)

  • 这并没有解决 OP 问题中的循环依赖问题。 (5认同)