EntityFramework系列:Repository模式与单元测试

时间:2023-11-26 10:59:20

1.依赖IRepository接口而不是直接使用EntityFramework

使用IRepository不只是架构上解耦的需要,更重要的意义在于Service的单元测试,Repository模式本身就是采用集合操作的方式简化数据访问,IRepository更容易Mock。先上图:

EntityFramework系列:Repository模式与单元测试

鉴于目前接触到的项目中,即使业务逻辑相对复杂的项目也只是应用逻辑复杂而非领域逻辑复杂,在实际使用中聚合根和单独Repository接口只是引入了更多的代码和类型定义,因此一般情况下使用泛型版本的Repository<T>接口即可。nopcommerce等开源项目中也是如此。Java中的伪泛型无法实现泛型版本的Repository<T>,简单的说你无法在Repository<T>的方法中获取T的类型。

 namespace Example.Application
{
public interface IRepository<T> where T : class
{
T FindBy(object id); IQueryable<T> Query { get; } void Add(T entity); void Remove(T entity); void Update(T entity); int Commit();
}
}

2.封装DbContext的依赖项

(1)定义一个通用的EfDbContext,将DbContext对IDbConnectionFactory、ConnectionString、实体类配置等的依赖封装到DbSettings中,既可以在使用使方便依赖注入也方便进行单元测试。


 namespace Example.Infrastructure.Repository
{
public class EfDbContext : DbContext, IDbContext
{
private DbSettings _dbSettings; public EfDbContext(IConfiguration configuration, ILogger logger, DbSettings dbSettings) : base(dbSettings.NameOrConnectionString)
{
this._dbSettings = dbSettings;
if (this._dbSettings.DbConnectionFactory != null)
{
#pragma warning disable
Database.DefaultConnectionFactory = this._dbSettings.DbConnectionFactory;
}
if (configuration.Get<bool>("database.log:", false))
{
this.Database.Log = sql => logger.Information(sql);
}
this.Database.Log = l => System.Diagnostics.Debug.WriteLine(l);
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder); modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
if (_dbSettings.EntityMaps != null)
{
foreach (var item in _dbSettings.EntityMaps)
{
modelBuilder.Configurations.Add((dynamic)item);
}
}
if (_dbSettings.ComplexMaps != null)
{
foreach (var item in _dbSettings.ComplexMaps)
{
modelBuilder.Configurations.Add((dynamic)item);
}
}
} public void SetInitializer<T>() where T : DbContext
{
if (this._dbSettings.Debug)
{
if (this._dbSettings.UnitTest)
{
Database.SetInitializer(new DropCreateDatabaseAlways<T>());
}
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<T>());
}
}
else
{
Database.SetInitializer<T>(null);
}
} public new IDbSet<T> Set<T>() where T : class
{
return base.Set<T>();
} public int Commit()
{
return base.SaveChanges();
}
}
}

(2)在DbSettings中按需定义依赖,这里将实体类的配置也通过DbSettings注入。


 namespace Example.Infrastructure.Repository
{
public class DbSettings
{
public DbSettings()
{
this.RowVersionNname = "Version";
} public string NameOrConnectionString { get; set; } public string RowVersionNname { get; set; }
public bool Debug { get; set; } public bool UnitTest { get; set; } public IDbConnectionFactory DbConnectionFactory { get; set; } public List<object> EntityMaps { get; set; } = new List<object>(); public List<object> ComplexMaps { get; set; } = new List<object>();
}
}

3.定义SqlServerDbContext和VersionDbContext,解决使用开放式并发连接时,MySql等数据库无法自动生成RowVersion的问题。

(1)适用于SqlServer、SqlServeCe的SqlServerDbContext


 namespace Example.Infrastructure.Repository
{
public class SqlServerDbContext : EfDbContext
{
private DbSettings _dbSettings; public SqlServerDbContext(IConfiguration configuration, ILogger logger, DbSettings dbSettings)
: base(configuration, logger, dbSettings)
{
this._dbSettings = dbSettings;
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Properties().Where(o => o.Name == this._dbSettings.RowVersionNname).Configure(o => o.IsRowVersion());
base.SetInitializer<SqlServerDbContext>();
}
}
}

(2)适用于Myql、Sqlite等数据库的VersionDbContext。使用手动更新Version,通过GUID保证版本号唯一。


 namespace Example.Infrastructure.Repository
{
public class VersionDbContext : EfDbContext
{
private DbSettings _dbSettings; public VersionDbContext(IConfiguration configuration, ILogger logger, DbSettings dbSettings)
: base(configuration,logger,dbSettings)
{
this._dbSettings = dbSettings;
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Properties().Where(o => o.Name == this._dbSettings.RowVersionNname)
.Configure(o => o.IsConcurrencyToken().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None));
base.SetInitializer<VersionDbContext>();
} public override int SaveChanges()
{
this.ChangeTracker.DetectChanges();
var objectContext = ((IObjectContextAdapter)this).ObjectContext;
foreach (ObjectStateEntry entry in objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added))
{
var v = entry.Entity;
if (v != null)
{
var property = v.GetType().GetProperty(this._dbSettings.RowVersionNname);
if (property != null)
{
var value = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
property.SetValue(v, value);
}
}
}
return base.SaveChanges();
}
}
}

4.使用XUnit、Rhino.Mocks和SqlServerCe进行单元测试

这是参考nopcommerce中的做法,nopcommerce使用的NUnit需要安装NUnit扩展,XUnit只需要通过Nuget引入程序包,看看GitHub上的aspnet源码,微软也在使用XUnit。


 namespace Example.Infrastructure.Test.Repository
{
public class CustomerPersistenceTest
{
private IRepository<T> GetRepository<T>() where T : class
{
string testDbName = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + @"\\test.sdf;Persist Security Info=False";
var configuration = MockRepository.GenerateMock<IConfiguration>();
var logger = MockRepository.GenerateMock<ILogger>();
var repository = new EfRepository<T>(new SqlServerDbContext(configuration,logger,new DbSettings
{
DbConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0"),
NameOrConnectionString = testDbName,
Debug = true,
UnitTest = true,
EntityMaps = new List<object> { new EntityTypeConfiguration<Customer>() }
}));
return repository;
} [Fact]
public void SaveLoadCustomerTest()
{
var repository = this.GetRepository<Customer>();
repository.Add(new Customer { UserName = "test" });
repository.Commit();
var customer = repository.Query.FirstOrDefault(o => o.UserName == "test");
Assert.NotNull(customer);
}
}
}

5.确保在ASP.NET中使用依赖注入时,配置DbContext的生命周期为Request范围


 namespace Example.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ObjectFactory.Init();
ObjectFactory.AddSingleton<IConfiguration, AppConfigAdapter>();
ObjectFactory.AddSingleton<ILogger, Log4netAdapter>();
ObjectFactory.AddSingleton<DbSettings, DbSettings>(new DbSettings { NameOrConnectionString = "SqlCeConnection", Debug = true });
ObjectFactory.AddScoped<IDbContext, SqlServerDbContext>();
ObjectFactory.AddTransient(typeof(IRepository<>), typeof(EfRepository<>));
ObjectFactory.Build();
ObjectFactory.GetInstance<ILogger>().Information(String.Format("Start at {0}",DateTime.Now));
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
} protected void Application_EndRequest()
{
ObjectFactory.Dispose();
}
}
}

依赖注入这里采用的是StructureMap。HttpContextLifecycle提供了Request范围内的生命周期管理但未定义在StructureMap程序包中,需要引入StructureMap.Web程序包。使用HttpContextLifecycle时需要在Application_EndRequest调用HttpContextLifecycle.DisposeAndClearAll()方法。