1 namespace Example.Infrastructure.Test.Repository 2 { CustomerPersistenceTest 4 { { + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + ; 8 var configuration = MockRepository.GenerateMock<IConfiguration>(); 9 var logger = MockRepository.GenerateMock<ILogger>(); 10 var repository = new EfRepository<T>(new SqlServerDbContext(configuration,logger,new DbSettings 11 { ), 13 NameOrConnectionString = testDbName, 14 Debug = true, 15 UnitTest = true, 16 EntityMaps = new List<object> { new EntityTypeConfiguration<Customer>() } 17 })); 18 return repository; 19 } 20 21 [Fact] SaveLoadCustomerTest() 23 { 24 var repository = this.GetRepository<Customer>(); }); 26 repository.Commit(); ); 28 Assert.NotNull(customer); 29 } 30 } 31 }
5.确保在ASP.NET中使用依赖注入时,配置DbContext的生命周期为Request范围1 namespace Example.Web 2 { MvcApplication : System.Web.HttpApplication 4 { Application_Start() 6 { 7 ObjectFactory.Init(); 8 ObjectFactory.AddSingleton<IConfiguration, AppConfigAdapter>(); 9 ObjectFactory.AddSingleton<ILogger, Log4netAdapter>(); , Debug = true }); 11 ObjectFactory.AddScoped<IDbContext, SqlServerDbContext>(); 12 ObjectFactory.AddTransient(typeof(IRepository<>), typeof(EfRepository<>)); 13 ObjectFactory.Build(); ,DateTime.Now)); 15 AreaRegistration.RegisterAllAreas(); 16 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 17 RouteConfig.RegisterRoutes(RouteTable.Routes); 18 BundleConfig.RegisterBundles(BundleTable.Bundles); 19 } Application_EndRequest() 22 { 23 ObjectFactory.Dispose(); 24 } 25 } 26 }
依赖注入这里采用的是StructureMap。HttpContextLifecycle提供了Request范围内的生命周期管理但未定义在StructureMap程序包中,需要引入StructureMap.Web程序包。使用HttpContextLifecycle时需要在Application_EndRequest调用HttpContextLifecycle.DisposeAndClearAll()方法。