在,我们引入了Repository模式和UnitOfWork模式。
探索还没有结束,我们引入。那用Unity做什么呢?
在上文中,我们手工定义了CustomerRepository中DbContext的,
1 DbContext context = new RETAILContext();2 DbContextAdapter contextAdaptor = new DbContextAdapter(context);3 4 IObjectSetFactory objectSetFactory = contextAdaptor;5 _repository = new Repository(objectSetFactory);6 7 IObjectContext objectContext = contextAdaptor;8 _uow = new UnitOfWork(objectContext);
但如果表数量过多,手工编码会变得非常繁琐,使用IoC容器提供的功能来解决。
1 IUnityContainer container = new UnityContainer() 2 .RegisterType(typeof(IRepository<>), typeof(Repository<>), new ContainerControlledLifetimeManager()) 3 .RegisterType(new ContainerControlledLifetimeManager()) 4 .RegisterType (new ContainerControlledLifetimeManager()) 5 .RegisterType (new ContainerControlledLifetimeManager()) 6 .RegisterType (new ContainerControlledLifetimeManager()) 7 .RegisterType (new ContainerControlledLifetimeManager()) 8 .RegisterType (new ContainerControlledLifetimeManager()); 9 10 ICustomerRepository customerRepository = container.Resolve ();
则在CustomerRepository中的配置会简介些,
1 public CustomerRepository(IUnityContainer container)2 {3 Mapper.CreateMap();4 Mapper.CreateMap ();5 6 _repository = container.Resolve >();7 _uow = container.Resolve ();8 }
显然同样的测试代码仍然可以工作,不再赘述。
最后,如果需要可以将UnityContainer注入到中,以备使用。
1 UnityServiceLocator locator = new UnityServiceLocator(container);2 ServiceLocator.SetLocatorProvider(() => locator);
完整代码和索引
EntityFramework用法探索系列
本文转自匠心十年博客园博客,原文链接:http://www.cnblogs.com/gaochundong/archive/2013/06/06/entityframework_usage_with_unity.html,如需转载请自行联系原作者