存储库是单例还是静态还是没有这些? [英] Is Repository Singleton or Static or None of these?

查看:24
本文介绍了存储库是单例还是静态还是没有这些?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP.NET 网站,它使用域驱动设计并使用存储库进行数据库操作.
我想知道单例存储库和静态存储库以及每次访问都会新建的简单存储库类的优缺点是什么?
如果有人可以比较和指导我使用其中的哪一个,我将不胜感激.

I have a ASP.NET web site which uses domain driven design and uses repository for its database operations.
I want to know that what is pros and cons of singleton repository and static repository and simple repository class which will new on every access?
further more if anyone can compare and guide me to use which one of them I will be appreciate.

推荐答案

静态和单例不是存储库模式的好解决方案.如果您的应用程序将来会使用 2 个或更多存储库怎么办?

Static and singleton aren't good solution for Repository pattern. What if your application will use 2 or more repositories in the future?

IMO 最好的解决方案是使用依赖注入容器并将您的 IRepository 接口注入需要它的类中.

IMO the best solution is to use a Dependency Injection container and inject your IRepository interface in the classes that need it.

我建议你阅读一本关于域驱动设计的好书和一本关于依赖注入的好书(比如 Mark Seeman 的 .NET 中的依赖注入).

I suggest you to read a good book about domain driven design and a good book about dependency injection (like Mark Seeman's Dependency Injection in .NET).

您有两个单例存储库:

class Repository<TEntity> {

  static Repository<TEntity> Instance { get { ... /*using sql server*/ } }
}

class Repository2<TEntity> {

  static Repository2<TEntity> Instance { get { ... /*using WCF or XML or any else */ } }
}

使用它们的服务必须具有对其中之一或两者的静态引用:

The services using them must have a static reference to one of them or both:

class OrderService {

    public void Save(Order order) { Repository<Order>.Instance.Insert(order); }
}

如果存储库是静态引用的,您如何使用 Repository2 保存订单?

更好的解决方案是使用 DI:

A better solution is using DI:

interface IRepository<TEntity> { ... }

class SqlRepository<TEntity> : IRepository<TEntity> { ....}

class OrderService {
    private readonly IRepository<TEntity> _repo;

    public OrderService(IRepository<TEntity> repo) { _repo = repo; }

    public void Save(Order order) { repo.Insert(order); }
}

这篇关于存储库是单例还是静态还是没有这些?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆