存储库是Singleton还是Static,还是都不是? [英] Is Repository Singleton or Static or None of these?

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

问题描述

我有一个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); }
}

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

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