如何使用简单的注入器,存储库和上下文 - 代码优先

 易_拉罐 发布于 2023-02-10 12:55

我正在尝试使用Simple Injector来创建我的存储库并在业务逻辑层中使用它(我也想使用PerWebRequest方法).

在DAL层我有:

public interface IRepository where T : class
{
    void Add(T entity);
    void Delete(T entity);
    void Delete(int id);
    void Update(T entity);
    T GetById(int Id);
    IQueryable All();
    IEnumerable Find(Func predicate);
}

并且:

public class EFRepository : IRepository, IDisposable where T : class
{
    #region Members
    protected DbContext Context { get; set; }
    protected DbSet DbSet { get; set; }
    #endregion

    #region Constructors

    public EFRepository(DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException("dbContext");
        Context = dbContext;
        DbSet = Context.Set();
    }

和我的背景:

public class PASContext : DbContext, IDbContext
{
    public DbSet Products { get; set; }
    public DbSet Users { get; set; }

    public PASContext()
        : base("PostAndSell")
    { }
}

正如您所看到的EFRepository,只有一个构造函数接受一个参数 - 这是因为我想使用Simple Injector创建上下文的实例,并在创建时将其传递给存储库.

在BLL中我有一个类ProductBLL,我想从数据库中获取该类中的所有产品(使用一些GetAll方法)并传递它,让我们说到HomeController.

我真的需要有人来跟我说话.

我首先从nuger安装正确的软件包(Simple Injector和Simple Injector ASP.NET Integration)

同样在我的global.asax.cs文件中,在Application_Start()函数I下添加了:

var container = new SimpleInjector.Container();

container.RegisterPerWebRequest, EFRepository>();

但是我在哪里创建Context实例?以及如何在业务层中访问它?

1 个回答
  • 由于您可能会有许多IReposotory<T>实现(对于产品,客户,员工等),因此最好如下所示进行单一的开放式通用注册IRepository<T>:

    container.Register(typeof(IRepository<>), typeof(EFRepository<>), Lifestyle.Scoped);
    

    范围生活方式定义为:

    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
    

    该注册确保简单的喷油器将返回EFRepository<Product>,每次IRepository<Product>请求,一EFRepository<Customer>IRepository<Customer>,等等,等等.

    由于您希望在同一DbContext请求中的所有存储库上使用相同的实例,因此您还应该DbContext使用范围生活方式注册:

    container.Register<DbContext, PASContext>(Lifestyle.Scoped);
    

    在BLL中我有一个ProductBLL类,我想从数据库中获取所有产品并将其传递给,让我们说HomeController

    在那种情况下,这ProductBLL对我来说似乎是一种无用的抽象.如果只是传递数据,您可以轻松地直接HomeController依赖IRepository<Product>.

    2023-02-10 12:59 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有