Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

entity framework - EF - and repository pattern - multiple contexts

I've faced some troubles with context in EF in ASP.MVC2.

I thought that best way to improve some operation on DataBase i've created Repository. My repo class adds, deletes, select many items so i don't need to write

(using <name>Context = new (... etc ...) ) { ... }

Repository eliminates initializing context for every operation, but don't dispose the context.

What is the best way to manage contexts? If i create other repository class and try to do any operation which will need objects from both contexts there is a problem.

Is there any other way or better way to implement repository, to manage contexts? Any interesting pattern?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A context is a unit of work, so you want one per web request.

Therefore, you should use constructor injection (i.e., a constructor argument) to supply a single context for all repositories, and dispose it at the end of the request.

Most DI frameworks will do this automatically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...