问题
We are about to start up a new project similar to a previous one. I could just copy the old design but I am not all too satisified with the old design.
It is a "standard" business system (sales,stocktaking,warehousing etc) built ontop of .Net 3.5 (Winforms MDI) with Entity Framework in the backend.
All forms inherit from a baseform (which inherits Windows.Form). The form exposes a property called ObjectContext, which on the first call instantiates a new ObjectContext. This makes up a pretty good UnitOfWork i think, having all data-access isolated in each form.
However.
I have encapsulated all queries and common CRUD in "poor mans repositories". These Repositories are exposed as properties of the ObjectContext.
So if I wanted to bind and order to a form I would call OrderLinesGrid = ObjectContext.OrderRepository.GetOrderLinesByID(orderID).
The OrderRepository gets a reference to the objectcontext created for the form, like this
(In my partial ObjectContext class)
Private _OrderRepository as OrderRepository
Public ReadOnly Property OrderRepository as OrderRepository
Get
if _orderrepository is nothing then
_orderrepository = New OrderRepository(me)
end if
return _orderrepository
End Get
End Property
What I do not like about this is:
The call to the repository is made through ObjectContext. Hence, I do not get abstraction between the query and the dataaccesslayer I would like.
For each new type in my Domain I need to create a property in my ObjectContext
My call to OrderRepository should just return domain objects and not worry about how it is persisted. Also, I cannot have each Repository have it's own ObjectContext since that would require me to Attach and Detach objects when referencing i.e Country to a Order.Country property.
I would appreciate any ideas and feedback on this design :)
回答1:
I suggest you research "onion" principle , Repository pattern and Luw pattern. There are many examples on the web.
Essentially you use POCO Model Core Project. No references to DAL project. You declare interfaces for the Repository and luw patterns in the CORE project.
So Now a
UI layer -> instantiate context and DAL Object eg repository -> inject into CORE services.
Also connected to this approach is Inversion of Control or dependency injection pattern.
If you use test driven development against Dummy Repositories you can make sure the design principles are adhered to.
来源:https://stackoverflow.com/questions/2302464/using-entity-framework-with-repository-pattern-in-winforms-mdi