我正在尝试使用 Simple Injector 创建我的存储库并在业务逻辑层中使用它(我也想使用 PerWebRequest 方法)。
在 DAL 层我有:
public interface IRepository<T> where T : class
{
void Add(T entity);
void Delete(T entity);
void Delete(int id);
void Update(T entity);
T GetById(int Id);
IQueryable<T> All();
IEnumerable<T> Find(Func<T, bool> predicate);
}
and :
public class EFRepository<T> : IRepository<T>, IDisposable where T : class
{
#region Members
protected DbContext Context { get; set; }
protected DbSet<T> DbSet { get; set; }
#endregion
#region Constructors
public EFRepository(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("dbContext");
Context = dbContext;
DbSet = Context.Set<T>();
}
和我的背景:
public class PASContext : DbContext, IDbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<User> Users { get; set; }
public PASContext()
: base("PostAndSell")
{ }
}
如你看到的EFRepository
只有一个带有一个参数的构造函数 - 这是因为我想使用 Simple Injector 创建上下文的一个实例,并在创建时将其传递到存储库。
在 BLL 我有一堂课ProductBLL
我想从数据库获取该类中的所有产品(使用一些 GetAll 方法)并将其传递给 HomeController 。
我真的需要有人跟我谈谈这件事。
我首先从 nuger 安装正确的包(简单注入器和简单注入器 ASP.NET 集成)
也在我的 global.asax.cs 文件中,位于Application_Start()
我添加的功能:
var container = new SimpleInjector.Container();
container.RegisterPerWebRequest<IRepository<Product>, EFRepository<Product>>();
但我在哪里创建 Context 实例?我如何在业务层访问它?