且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

需要Repository模式和依赖注入的更深入的例子

更新时间:2023-12-02 11:09:34

这是我的方式通常做在我的实现。

This is the way i usually do it in my implementations.

有一个通用接口,IEntityRepository它定义了基本的CRUD结构。在我实现我定义了以下成员:

A generic interface, IEntityRepository which defines your basic CRUD structure. In my implementations i define the following members:


  1. 插入

  2. 更新

  3. 删除

  4. 获取

  5. GetPaged

  6. GETALL

  7. 找到(这是使用predicate生成器生成的where子句)

我创建另一个接口IMyentityRepository它继承IEntityRepository。这让我添加任何特定实体成员,仍然能够当我需要使用DI。然后我创建密封类MyentityRepository它继承IMyentityRepository并实现所有成员。

I create another interface IMyentityRepository which inherits IEntityRepository. This allows me to add any entity-specific members and still be able to use DI when i need to. I then create my sealed class MyentityRepository which inherits IMyentityRepository and implements all members.

当您使用依赖注入,您可以注册您的具体类型MyentityRepository接口(IMyentityRepository)。

When you use Dependency Injection you can register your interface (IMyentityRepository) for concrete type of MyentityRepository.

在我而言,我实际上并没有完成。我对仓库之上创建一个服务层封装,并在更广泛的方式揭露它。例如,假设您想为您的用户的帐户可能涉及比简单的创建一个数据库记录更多的工作。在你的服务,你有一个叫做CREATEUSER()成员可以调用多个库成员的执行。
在同是作为我的仓库层我的业务层构建。我有IEntityService共同CRUD成员,IMyentityService为实现特定实体成员和MyentityService。 MyentityService类将需要IMyentityService的一个实例(您可以使用您选择的IoC框架注入的话)你的服务层也可以做验证和任何业务逻辑。我做验证的控制器。那么,在技术上,我调用它在我的控制器和得到的结果,我可以再写入的ModelState。

In my case, i wasn't actually done. I created a service layer on top of the repository to encapsulate it and expose it in a more general way. For instance, say you want to create an account for your user which may involve more work than simply creating a database record. In your service, you'd have a member called CreateUser() which may call multiple repository members in its implementation. My service layer is built in the same was as my repository layer. I have IEntityService for common CRUD members, IMyentityService for entity-specific members and MyentityService for implementation. MyentityService class would require an instance of IMyentityService (You can inject it with your IoC framework of choice) Your service layer may also do validation and any business logic. I do validation in controllers. Well, technically, i invoke it my controllers and get the result that i can then write to ModelState.

希望这有助于一点。