如何使用简单的注入器,存储库和上下文 – 首先编码
我正在尝试使用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
。
- 如何在ASP.NET标识中编辑用户
- 构建语言切换器 – 仅限2种语言 – ASP.NET MVC
- 当前上下文中不存在名称“xyz”
- 条件ModelState合并
- 将null赋给可空int时出错 – “值’null’对于属性无效”
- OAuthWebSecurity与Facebook未按预期使用电子邮件权限
- 找不到方法:’Void Newtonsoft.Json.Serialization.DefaultContractResolver.set_IgnoreSerializableAttribute(Boolean)’
- NHibernate的工作单元/存储库管理器?
- 在数据库中存储大型文件会导致类型为“System.OutOfMemoryException”的exception