In the previous article, we introduced unity to help build various repository and unitofwork.
At the same time, we inject unitycontainer into the implementation of servicelocator,
1Unityservicelocator locator =NewUnityservicelocator (container );2Servicelocator. setlocatorprovider () => Locator );
If the number of tables is too large, it is too cumbersome to inject ixxxrepository into the service class. To find a concise method, we will introduce servicelocator and static classes here, although both methods are not suitable for unit testing.
1 Public Static Class Repository 2 { 3 Public Static Irepository <customer> MERs 4 { 5 Get { Return Servicelocator. Current. getinstance <irepository <customer> ();} 6 } 7 8 Public Static Void Commit () 9 { 10 Servicelocator. Current. getinstance <iunitofwork> (). Commit (); 11 } 12 }
If we have a new table definition, we only need to add a new attribute. For example, add a supplier table supplier.
1Public StaticIrepository <supplier>Suppliers2 {3Get{ReturnServicelocator. Current. getinstance <irepository <supplier>();}4}
In this way, our businessCodeIt can be simpler,
1 Public Void Insertcustomer (domainmodels. Customer customer) 2 { 3 Customer entity = Mapper. Map <domainmodels. Customer, Customer> (Customer ); 4 5 Repository. Customers. insert (entity ); 6 Repository. Commit (); 7 8 Customer. ID = Entity. ID; 9 } 10 11 Public Void Updatecustomer (domainmodels. Customer customer) 12 { 13 Customer entity = repository. MERs. Query (). Single (C => C. ID = Customer. ID ); 14 15 Entity. Name = Customer. Name; 16 Entity. Address = Customer. address; 17 Entity. Phone = Customer. Phone; 18 19 Repository. MERs. Update (entity ); 20 21 Repository. Commit (); 22 }
Complete code and Indexing
How to Use entityframework
- (1) databasefirst
- (2) codefirst
- (3) codefirst smooth API
- (4) repository and unitofwork
- (5) Introduce unity
- (6) static repository
- (7) thread security practices
- (8) Transaction Processing
Download complete code