Is DDD necessary in my WPF+WCF scenario? - wcf

I am developing a WPF application, that connects to several WCF services (that work with LINQ-TO-EF).
The WPF is designed in MVVM fashion.
For each WCF Service I have the following:
Service Layer DLL - this includes the service interface, service implementation. the service implementation just creates BL objects and calls methods on them
Service BL Layer DLL - this includes a manager factory (factory creates UserManager, TaskManager etc). Each manager has an interface + implementation (for unit-testing purposes and DI). For example - TaskManager has 'GetTasks', 'CheckTaskIsValid' etc. In addition, the BL Layer has a 'Trasnlator' class to translate from Data-Entity to DTO. The BL manager methods return DTOs to the service layer.
In addition to the above, all the service BLs reference the Data Access Layer DLL that includes:
EDMX file with tables from MS SQL Server
Auto-Generated DbContext + POCO entities
Query providers (used by BL manager classes). Each query provider has an interface+implementation for unit-testing and DI purposes.
DbContext factory - interface+implementation, for unit-testing and DI purposes.
The services are in CQS design (Command-Query-Seperation, not to mix with CQRS), meaning that there is one service responsible for querying only and one service responsible for sending commands.
I am using DI (using AutoFac) through my WCF Host Project that hosts all the services (I implemented IInstanceProvider, so that I can inject dependencies to the services).
I did not implement my own repositories or unit-of-work, because DbContext already is UoW and Repositories.
Is this design flawed ?
I have read a lot of posts about DDD, and I know that my design is not DDD.
My question is - is my design good enough ? Do I need to refactor all my code towards DDD ? (using aggregates and root aggregates etc).
I have tried to provide as much detail as possible about the design, so I hope I don't get answers like 'Your question is too general' or 'Need some examples'... Any helpful information would be very much appreciated !

Yes, you have not DDD design, but not-DDD doesn't means bad design. I think when your system is testable and flexible for further development, scales good for your needs - than you have good system design for your needs.
All other sounds good except:
I did not implement my own repositories or unit-of-work, because
DbContext already is UoW and Repositories.
Not implementing your UoW and Repositories means you are tightly coupled to Entity Framework and it could be problems with testability. But you can cover it with integration test again test database. Unit tests for database logic sometimes tests itself.
Do you need DDD? Maybe when system will be more complex than evolutional you will come to DDD and to CQRS. But when it's enough for you, easy to maintain and for further development, testable, scaling, when system is not fragile, than I think, it's better to focus on business needs

Related

How Implement CRQS in DDD

If someone tries to implement the CQRS pattern without repository in DDD, in which layer should it be done? Infrastructure or Application Layer?
If you mean the implementation of the handlers of the queries and commands, it's done in the application layer.
But you need a repository to abstract the technological implementation outside of use cases/interactors (application layer).
The Infrastructure layer is responsible for encapsulating technology. You can find there the implementations of database repositories for storing/retrieving business entities, message brokers to emit messages/events, I/O services to access external resources, framework related code and any other code that represents a replaceable detail for the architecture.

What is the path forward for changetracking complex entity relationships if Self Tracked Entities are not recommended anymore?

I have been using EF since it first came out. Used to hand build POCOs in 3.5 and was glad to see Self Tracked Entities(STE) in EF4.0.
I have use STEs in a couple of very large projects(500+ entities, some with multiple models). In these projects I use a generic Repository and a generic Unit of Work to persist the entities i.e. 2 small generic classes no mapping. By electing a core entity as the "aggregrate root", other entities are added and updated on the client side and the core entity graph containing these changes is sent to the WCF service and used in the Logic Layer which creates the Repository<[core entity]> and uses the UnitOfWork<[core entity]>.Save(Repository<[core entity]>) to persist the STEs and their children to the database.
Now Microsoft is recommending that we not use STEs. See this article
So my question is, What is(are) the patterns that are now recommended by Microsoft for applications that are persisting client changes to WCF Services that use EF?
I created a EF5 Model and examined the generated code. The there are no attributes for a WCF Service i.e. DataContract, DataMember etc
EF4 had a "ADO.NET DbContext Generator with WCF Support" template, but there isn't a EF5 equivalent.
One site suggested I should use a partial class file and decorate the same properties in that file with these attributes. But unless .net 4.5 has introduced partial properties, I cannot see how that can be done.
Another blog suggested using DTO and Automapper, which means more mapping which is error prone; especially when entity fields change type.
So now that DBContext generated code classes are not Service enabled, does this mean that we need to write another set of classes (POCOs) that:
needs to be mapped FROM the DBContext generated code classes after querying the database.
holds the data state for the WCF Service client(s)
is updatable by that client(s)
is mapped by the client(s)
has the ability to hold changed state so this can be sent back to the WCF Service
needs to be mapped TO the DBContext generated code classes for persistence
It seems we just took a great leap backwards to EF3.
If you code both client and service that runs on your hardware, you don't need to be concerned about data structures at the client as they belong to you.
If you also need to expose some of your service methods to non.NET clients you should do the 5 points above for those services anyway and use DTOs and Automapper in those occasions.These should be in a different WCF Service but implemented against the same Logic Layer, after mapping.
But how many of these type of non.NET client services are be created in the day to day building of web applications in most software teams?
This latest recommendation is confusing as it has not been explained as to WHY STEs are ALWAYS ill-conceived and what now, are the recommended patterns to be used for persisting client changes to WCF Services that use EF.
Can anybody inform me where I can find a good resource that solves this architectural design issue?
P.S.
Please don't recommend WCF Data Services or WCF RIA as we need a lot of control over how your data is retrieved and saved by clients.
Please don't recommend Code First as we use Database First as we want to have and need to control the structure of that database and not have to generated for us.
Ok so i thought the same thing when I first read this article, it seems a bit weird to deprecate a whole branch of EF like this and the intention wasn't terribly well communicated (IMO). I think a couple of things are important here:
STEs as referred to in this article refer to object context based self tracking entities (which act a little like autonomous contexts)
ObjectContext is generally being moved away from in favor of the cleaner DbContext structure (this is for both DB first and Code First)
STEs != DB first generation, you can still use an EDMX model in EF and this isn't likely to change.
When i originally saw this article I mistook STEs for POCO Proxy entities which are still available and AFAIK there are no plans to deprecate. (these achieve a similar technical solution to the problem of change detection but with a nicer interface. Check out this article for the differences EF4: Difference between POCO , Self Tracking Entities , POCO Proxies
So what does this all mean
Basically STEs in terms of the old implementation of a change tracker are being deprecated in favor of the newer forms of change tracking (Snapshot or POCO Proxies). This means that if snapshot tracking doesn't suit you you should look into POCO Proxies which are similar to the old STEs.
You can still use all previous techniques for context generation (DB First, Model First, Code First, and DB-> Code)

Making OR/M loosely coupled and abstracted away from other layers

In an n-tier architecture, the best place to put an object-relational mapping (OR/M) code is in the data access layer. For example, database queries and updates can be delegated to a tool like NHibernate.
Yet, I'd like to keep all references to NHibernate within the data access layer and abstract dependencies away from the layers below or above it. That way, I can swap or plug in another OR/M tool (e.g. Entity Framework) or some approach (e.g. plain vanilla stored procedure calls, mock objects) without causing compile-time errors or a major overhaul of the entire application. Testability is an added bonus.
Could someone please suggest a wrapper (i.e. an interface or base class) or approach that would keep OR/M loosely coupled and contained in 1 layer? Or point me to resources that would help?
Thanks.
It sounds like you are looking for the repository pattern. If you need more decoupling, you can inject the data dependencies with an Inversion of Control container.
Service Facade Pattern is one name. Simple contracts between business logic and data layer.
Service classes or beans (call it what you want) define and implement the contract, and orchestrate the lower data layer, often handling the transactional logic across data objects.
In Spring, you define an Interface, and then implement it. One implementation might be an OR/M, another might be raw JDBC or ADO.NET. In some frameworks, Aspect Oriented Programming allows you to inject declarative transactional logic without writing any code. It saves a lot of headache.
One caveat: When dealing with some OR/Ms like Hibernate, there is the use of proxy classes. This does pollute things, because there are a few instances where the proxy classes cause problems. In my opinion, that is an implemtation detail that should not escape the service layer. But with Hibernate, it does. Not sure about the .NET implementation.

How to build a WCF service that exposes your business layer?

WCF promotes good design by using interfaces and contracts etc. What baffles me is that, for example in my case if I have 2 sets of business functionality like ICustomerMgmtBIZ
and IProductMgmtBiz. If these two are ServiceContracts, and I have an interface like
IBusinessService:IProductMgmtBIZ,ICustomerMgmtBIZ
and implementation class BusinessService. I see that BusinessService class will be having too much implementation. The workaround I have been using so far is by implementing partial classes.
So bluntly put, can a WCF service have only 1 implementation and 1 service contract ??
No, it is possible to implement more than one Service contract on a WCF Service type (the class that is attributed with the ServiceBehavior attribute), since it is just a matter of having the class implement multiple interfaces. If you are using any of the Visual Studio templates or other kinds of code generators, this may not be immediately clear. However, although you can implement more than one Service Contract interface on a Service type, it does not do you much good if you need the service, presumably a singleton in this case(?), to behave as one service. IBusinessService implies that you need all of the service's functionality to be callable from one client proxy, so that all operations may operate in the same logical session (similar to ASPX web session). If that is not the case, then you are free to define individual proxies for each contract interface, but that will also require that you support one endpoint for each contract.
Is it an absolute requirement that you can only have on WCF ServiceHost instance for your implementation? What factors are influencing your decision?
By the way, partial classes do not trouble me anymore. The idea of splitting out code into multiple files now seems rather natural. For example, storing partial classes in files like ServiceType_IProductMgmtBiz.cs and ServiceType_ICustomerMgmtBIZ.cs seems natural enough, in addition to storing the core logic in ServiceType.cs.
Finally, the following question might be of use...
WCF and Interface Inheritance - Is this a terrible thing to do?
Bluntly put, no - sort of - yes, but. Any workaround is non-optimal and involves using an "IBlank" as a master WCF interface (where your interfaces derive from IBlank), and two endpoints, one implementing IProductMgmtBIZ and the other implementing ICustomerMgmtBIZ. I don't have my dev machine in front of me, this might involve some other overrides. So, at the WCF level you're screwed unless you want to have two WCF ServiceHosts (which is perfectly reasonable).
In short, the workaround is inelegant. Its easier to have two WCF endpoints on the same port with a different extension.

How to use the single responsibility principle in large wcf services?

We're using about 7 services at the moment. There quite large.
Does anyone have any experience with the single responsibility principle and WCF services? Does this mean that you'll end up with lot's of small contracts? If so, how do you manage these in your application?
I think you are confusing single responsibility with interface segregation.
From the client/service interface perspective, you should keep your contracts lean and mean. See below for an example of that.
On the SRP side of things, that should be entirely internal to the service implementation and the client should not be aware of this. If you service code is too large, split it up into classes. Then have your service code, at least initially, act as a facade and forward all the calls to the relevant objects. Later on, you have the option of spliting your service into multiple services. But be aware, that SOA and object oriented design, although overlap, are separate and have different requirements.
Interface segregation example: We have a service here at work that we use to do various functions on some business objects. The original service had one interface. As it grew, we realized we had three family of methods: data object persistence, business updates, business analysis. We split up into three contracts. Our client/service implements all 3, so the only thing we had to do was split the contract into three and setup two additional endpoints in our WCF configuration. Very simple.
Hope this helps.
I would suggest you listen to this podcast on the hanselminutes :
SOLID Principles with Uncle Bob - Robert C. Martin
It would help understand things better. . .
You could apply facade pattern for the web service that interface with the client, and in your implementation code you can apply single responsibility to make it maintainable.