Csharp/C#教程:如何使用简单的注入器,存储库和上下文 – 首先编码分享


如何使用简单的注入器,存储库和上下文 – 首先编码

我正在尝试使用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()函数下:

 var container = new SimpleInjector.Container(); container.RegisterPerWebRequest<IRepository, EFRepository>(); 

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

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

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

范围生活方式定义为:

 container.Options.DefaultScopedLifestyle = new WebRequestLifestyle(); 

此注册确保Simple Injector将在每次请求IRepository时返回EFRepository ,为IRepository提供EFRepository IRepository ,依此类推,等等。

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

 container.Register(Lifestyle.Scoped); 

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

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

上述就是C#学习教程:如何使用简单的注入器,存储库和上下文 – 首先编码分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1269765.html

(0)
上一篇 2022年11月22日
下一篇 2022年11月22日

精彩推荐