Accessing Domain Driven Design Class LIbraries from a WCF Service - wcf

I need some help clarifying how I should be setting up my project. My solution structure is as follows:
Company.DataTransferObjects
--AdminDTO.cs
--CustomerDTO.cs
Company.DataTransferObjects.Helpers
Company.Infrastructure.DomainServices
--Admin
---AdminService.cs
--Customer
--CustomerService.cs
Comapny.Infrastructure.Repositories
--Admin
---AdminRepository.cs
--Customer
---CustomerRepository.cs
Company.Domain
--Admin
---Admin.cs
---IAdminRepository.cs
--Customer
---Customer.cs
---ICustomerRepository.cs
Company.WebServices
--WebApi.cs
--IWebAPI.cs
My questions are as follows:
1) Does my set-up look right to you?
2) DTOs. From the web service's perspective, where should the DTOs be created?
Should I be creating the DTOs in an independent class library and referencing
them from the WebService or should they be part of my web service project?
Also, it is not clear to me how my DTOs should be interacting with my Domain objects.
Can somebody please explain their purpose from a program flow point of view and, specifically, if you were creating a WCF service how you would be manipulating them?
3) Domain Services. I am still having a hard time wrapping my mind around the purpose of Domain Services. Is this what is exposing the operational functionality that is not hitting the database and requires repository methods that cannot be accessed directly?
In other words, is a Domain Service a method that manipulates multiple repository methods? So, if my WCF service is calling data that can be accessed via a repository method, then that is what it should do. But, if it requires data that is the result of multiple repository methods, then this should be done via domain services?
4) Where does the Facade Pattern fit in a the DDD architecture?
Please excuse my confusion, I am trying to understand. It would be a serious help if you could tell me "what" I should be accessing from my WCF service.
Thanks!

going in reverse order on your questions:
4) Your web services are a facade to your domain, effectively.
3) Domain services can hit the DB too, they're typically the main API that consuming code should use to talk to your domain on anything that involves more than a single entity, or for things that represent a series of transactional steps. Some folks consider Repositories to be a special case of Domain Services (Rather than being an either/or). I usually consider my Services to be my domain's public interface.
2) DTO's are normally useful when you are (or plan to eventually) crossing physical boundaries. Anytime you think you might need to serialize something (e.g. into a SOAP message), you want to think about a DTO. SO in your case, your WCF project would use DTOs as its DataContracts, but internally it might use your domain objects (unless you expect your domain to sit in a different app domain or on a different physical box).
1) It's all personal preference; your layout doesn't look unreasonable, though it's different than how I normally organize.

Related

WCF SOA naming conventions

I have an class library called ServiceLayer which acts as a repository for a ASP.NET MVC application This service layer has a references to a WCF Service called ProfileService which contains Profile methods to perform CRUD operations on a database etc.
I now need to allow mobile devices to communicate with my application so I have created another WCF Service called ProfileService. This service has a reference to the ServiceLayer class library and makes calls to it to undertake Profile operations.
Now this is quite confusing as I now have 2 ProfileServices. The first communicating with my database etc and exposing itself to my service layer. The second communicating with my service layer and exposing itself to mobile devices.
What is the best way to name your services in a SOA environment to avoid confusion of which type is which? especially when mapping between types.
I may also want to create another service which acts as an API to users of the system. What would I name this service ProfileAPI?? I know each ProfileService is in its own namespace but this doesnt help with readability when creating AutoMapperSettings or performing manual mapping.
So if anybody out there knows of a good way to name services in this environment it would be much appreciated.
You are looking for a Service Facade
You would end up with a Facade, which is just a specialized interface into your real service. You would define the different services as needed (mobile, users, database)

OData based WCF service or regular WCF service for Silverlight application

I have just started evaluating whether or not I should be using OData influenced wcf data services or a standard WCF service application as the primary data source for Silverlight applications. I would like your thoughts on which is a better way under what situation/circumstance. What is lighter over the wire, easier to maintain, etc.
What I have gathered so far is:
There are no Wcf data service templates in VS2010 that I know of, and I will need to create a asp.net web project first and then add a wcf data service, so its going to affect how I structure my projects.
WCF Data services expose actual table names over the service. I don't know yet of a way I can alias them and I'm not sure its a good idea to let the world know my table structure
In a standard wcf service I will need to write linq queries against the EF or Domain service classes on the service side, while in a data service I can move that processing logic to the client.
At first glance examining the classes exposed by the wcf data services seem easier to read and understand than those exposed by the EF
Do add your thoughts on this..
Thanks for your time.
There are no Wcf data service
templates in VS2010 that I know of,
Not project template - just an item template (for use inside an ASP.NET web site or web app). WCF DataServices are very tightly coupled to HTTP, so they only make sense in a web site/app.
WCF Data services expose actual table
names over the service.
NO ! At least not necessarily. The whole point of EF is that you can decouple the actual physical structure of your database from the (conceptual) model that gets exposed. You can totally rename entities, you can map several entities onto a single table, split up an entity over several tables, you can leave out attributes - anything you like!
At first glance examining the classes
exposed by the wcf data services seem
easier to read and understand than
those exposed by the EF
I doubt it - because by default, WCF Data Services will use a Linq-to-SQL or EF model as their basis, really. You can make that as simple or as complicated as you like.
Using a "regular" WCF service allows you to use the netTcpBinding for much faster performance (thanks to binary message encoding vs. textual messages for other bindings), when using your Silverlight 4 app in a company-internal network (doesn't work for internet scenarios) - not something you can do with WCF DataServices.
The main difference in my opinion is the SOAP vs. REST difference:
SOAP (traditional WCF) is oriented towards methods - you think and design your system in terms of methods - things you can do (GetCustomer, SaveOrder etc.)
REST (the WCF DataServices approach) is all about resources, e.g. you have your resources and collections of resources (e.g. Customers) and you expose those out to the world, with standard HTTP verbs (GET, POST, PUT, DELETE) instead of separate specific methods that you define
So both approaches have their pros and cons. I guess the most important question is: what kind of app are you creating, and what kind of user audience are you targetting?
Update:
for intranet / internal apps, I would think the advantage of a netTcpBinding (binary encoding) would justify using a classic WCF service - also for data-intensive apps, I personally find a method-based approach (GetCustomer, SaveCustomer) to be easier to use and understand
for a public-facing app, using HTTP and being as interoperable as possible is probably your major concern, so in that scenario, I'd probably favor the WCF Data Service - easy to use, easy to understand URLs for the user

good practice: REST API as the interface between the interface layer and business layer?

I was thinking about the architecture of a web application that I am planning on building and I found myself thinking a lot about a core part of the application. Since I will want to create, for example, an android application to access it, I was already thinking about having an API.
Given the fact that I will want to have an external API to my application from day one, is it a good idea to use that API as an interface between the interface layer (web) and the business layer of my application? This means that even the main interface of my application would access the data through the API. What are the downsides of this approach? performance?
In more general terms, if one is building a web application that is likely to need to be accessed in different ways, is it a good architectural design to have an API (web service) as the interface between the interface layer and business layer? Is REST a good "tool" for that?
Sounds like you've got two questions there, so my answer is in two parts.
Firstly, should you use an API between the interface layer and the business layer? This is certainly a valid approach, one that I'm using in my current project, but you'll have to decide on the benefits yourself, because only you know your project. Possibly the largest factor to consider is whether there will be enough different clients accessing the business layer to justify the extra development effort in developing an API? Often that simply means more than 1 client, as the benefits of having an API will be evident when you come to release changes or bug fixes. Also consider the added complexity, the extra code maintenance overhead and any benefits that might come from separating the interface and business layers such as increased testability.
Secondly, if you implement an API, should you use REST? REST is an architecture, which says as much about how the remainder of your application is developed as it does the API. It's no good defining resources at the API level that don't translate to the Business Layer. Rest tends to be a good approach when you want lots of people to be able to develop against your API (like NetFlix for example). In the case of my current project, we've gone for XML over HTTP, because we don't need the benefits that Rest generally offers (or SOAP for that matter).
In general, the rule of thumb is to implement the simplest solution that works, and without coding yourself into a corner, develop for today's requirements, not tomorrow's.
Chris
You will definitely need need a Web Service layer if you're going to be accessing it from a native client over the Internet.
There are obviously many approaches and solutions to achieve this however I consider the correct architectural guideline to follow is to have a well-defined Service Interface on the Server which is accessed by the Gateway on the client. You would then use POCO DTO's (Plain old DTO's) to communicate between the endpoints. The DTO's main purpose is to provide optimal representation of your web service over the wire, it also allows you to avoid having to deal with serialization as it should be handled transparently by the Client Gateway and Service Interface libraries.
It really depends on how to big your project / app is whether or not you want want to go through the effort to mapping your DTO's to the client and server domain models. For large applications the general approach would be on the client to map your DTO's to your UI Models and have your UI Views bind to that. On the server you would map your DTO's to your domain models and depending on the implementation of the service persist that.
REST is an architectural pattern which for small projects I consider an additional overhead/complexity as it is not as good programattic fit compared to RPC / Document Centric web services. In not so many words the general idea of REST is to develop your services around resources. These resources can have multiple representations which your web service should provide depending on the preferred Content-Type indicated by your HTTP Client (i.e. in the HTTP ACCEPT HEADER). The canonical urls for your web services should also be logically formed (e.g. /customers/reports/1 as opposed to /GetCustomerReports?Id=1) and your web services would ideally return the list of 'valid states your client can enter' with each response. Basically REST is a nice approach promoting a loosely-coupled architecture and re-use however requires more effort to 'adhere' to than standard RPC/Document based web services whose benefits are unlikely to be visible in small projects.
If you're still evaluating what web service technology you should use, you may want to consider using my open source web framework as it is optimized for this task. The DTO's that you use to define your web services interface with can be re-used on the client (which is not normally the case) to provide a strongly-typed interface where all the serialization is taken for you. It also has the added benefit of enabling each web service you create to be called by SOAP 1.1/1.2, XML and JSON web services automatically without any extra configuration so you can choose the most optimal end point for every client scenario, i.e. Native Desktop or Web App, etc.
My recent preference, which is based on J2EE6, is to implement the business logic in session beans and then add SOAP and RESTful web services as needed. It's very simple to add the glue to implement the web services around those session beans. That way I can provide the service that makes the most sense for a particular user application.
We've had good luck doing something like this on a project. Our web services mainly do standard content management, with a high proportion of reads (GET) to writes (PUT, POST, DELETE). So if your logic layer is similar, this is a very reasonable approach to consider.
In one case, we have a video player app on Android (Motorola Droid, Droid 2, Droid X, ...) which is supported by a set of REST web services off in the cloud. These expose a catalog of video on demand content, enable video session setup and tear-down, handle bookmarking, and so on. REST worked out very well for this.
For us one of the key advantages of REST is scalability: since RESTful GET responses may be cached in the HTTP infrastructure, many more clients can be served from the same web application.
But REST doesn't seem to fit some kinds of business logic very well. For instance in one case I wrapped a daily maintenance operation behind a web service API. It wasn't obvious what verb to use, since this operation read data from a remote source, used it to do a lot of creates and updates to a local database, then did deletes of old data, then went off and told an external system to do stuff. So I settled on making this a POST, making this part of the API non-RESTful. Even so, by having a web services layer on top of this operation, we can run the daily script on a timer, run it in response to some external event, and/or have it run as part of a higher level workflow.
Since you're using Android, take a look at the Java Restlet Framework. There's a Restlet edition supporting Android. The director of engineering at Overstock.com raved about it to me a few years ago, and everything he told us was true, it's a phenomenally well-done framework that makes things easy.
Sure, REST could be used for that. But first ask yourself, does it make sense? REST is a tool like any other, and while a good one, not always the best hammer for every nail. The advantage of building this interface RESTfully is that, IMO, it will make it easier in the future to create other uses for this data - maybe something you haven't thought of yet. If you decide to go with a REST API your next question is, what language will it speak? I've found AtomPub to be a great way for processes/applications to exchange info - and it's very extensible so you can add a lot of custom metadata and yet still be eaily parsed with any Atom libraries. Microsoft uses AtomPub in it's cloud [Azure] platform to talk between the data producers and consumers. Just a thought.

Designing WCF data contracts and operations

I'm starting to design a wcf service bus that is small now but will grow as our business grow so I'm concerned about some grwoing problems and also trying not to YAGNI too much. It's a e-commerce platform. The problem is I'm having too many second thoughts about where to put stuff. I will give a scenario to demonstrate all my questions.
We have an e-commerce website that sells products and ultimately deliveries them. For this we have a PlaceOrder service which, among other parameters, expects an Address object that in this context (our website placing an order) is made of City, Street and ZipCode.
We also do business with partners that use our platform only to sell products. They take care of the delivery. For this scenario we have a PlaceOrderForPartner service that, among other objects, expects an Address object. However, in this context (partner placing an order) the Address object is made of different information that is relevant only to a order placed by partner.
Given this scenario I have several questions:
1) How to organize this DataContracts objects in namespaces and folders in my Solution? I thought about having a folder per-context (Partner, Customer, etc) to keep the services and the DataContracts.
So I would have
- MySolution.sln
- Partner (folder)
- PartnetService.svc
- DataContracts (folder)
- Address
- Customer (folder)
- Customer.svc
- DataContracts (folder)
- Address
Using this way I would have a namespace to place all my context-specific datacontracts.
2) What about service design? Should I create a service for each one that might place and order and create a PlaceOrder method inside it like this:
Partner.svc/PlaceOrder
Customer.svc/PlaceOrder
or create an Order service with PlaceOrderForPartner and PlaceInternalOrder like this:
Order.svc/PlaceOrderForPartner
Order.svc/PlaceOrderForCustomer
3) Assuming that I pick the first option in the last question, what should I do with the operations that are made on the order and common to Partner and Customer?
4) Should I put DataContracts and Service definition in the same assembly? One for each? Everything with the service implementation?
5) How to name input and output messages for operations? Should I use the entities themselves or go for OperationNameRequest and OperationNameResponse template?
Bottom line my great question is: How to "organize" the datacontracts and services involved in a service creation?
Thanks in advance for any thoughts on this!
Besides what TomTom mentioned, I would also like to add my 2 cents here:
I like to structure my WCF solutions like this:
Contracts (class library)
Contains all the service, operations, fault, and data contracts. Can be shared between server and client in a pure .NET-to-.NET scenario
Service implementation (class library)
Contains the code to implement the services, and any support/helper methods needed to achieve this. Nothing else.
Service host(s) (optional - can be Winforms, Console App, NT Service)
Contains service host(s) for debugging/testing, or possibly also for production.
This basically gives me the server-side of things.
On the client side:
Client proxies (class library)
I like to package my client proxies into a separate class library, so that they can be reused by multiple actual client apps. This can be done using svcutil or "Add Service Reference" and manually tweaking the resulting horrible app.config's, or by doing manual implementation of client proxies (when sharing the contracts assembly) using ClientBase<T> or ChannelFactory<T> constructs.
1-n actual clients (any type of app)
Will typically only reference the client proxies assembly, or maybe the contracts assembly, too, if it's being shared. This can be ASP.NET, WPF, Winforms, console app, other services - you name it.
That way; I have a nice and clean layout, I use it consistently over and over again, and I really think this has made my code cleaner and easier to maintain.
This was inspired by Miguel Castro's Extreme WCF screen cast on DotNet Rocks TV with Carl Franklin - highly recommended screen cast !
You start wrong on th highest level.
It should not be "PlaceOrder" service, but "OrderManager". Maybe you want to add more service functions later - like inquiring for orders, cancel orders, change orders - who knows. In general, I would keep the number of "services" (.svc) small and add methods there. Otherwise you end up with a HUGH overhead for using them, in code - without any real benefit.
Why separate between partners and customers? I am sure with 15 minutes of data design, you could break things down to exactly ONE data structure so you could have only one service. If not... make that two methods on one interface, limit by security. But I seriously would NOT like two programs for that. Rather have two address fields - "Address" and "PartnerInfo", and only one can be set (other has to be null), checked in the logic.
Separate out into two projects. Interfaces, data contracts go into a separate project (blabalbla.Api) so that customers can actually get the DLL if they want - at least it makes things a lot easier on your end, you can rely on "shared type", no need to generate the wrappers internally. Allows a lot better testing (as sub-projets dont forget to regenerate the wrappers.... which may lead to errors when testing them).
I always put the implementation into a "blabla.Service" project. Url would be "Services.blabla.com/" in a subdomain (or "api.blabla.com", depends mostly on mood, but lately I am going for api mostly) - separates thigns out from the main website.

WCF - Domain Objects and IExtensibleDataObject

Typical scenario. We use old-school XML Web Services internally for communicating between a server farm and several distributed and local clients. No third parties involved, only our applications used by ourselves and our customers.
We're currently pondering moving from XML WS to a WCF/object-based model and have been experimenting with various approaches. One of them involves transferring the domain objects/aggregates directly over the wire, possibly invoking DataContract attributes on them.
By using IExtensibleDataObject and a DataContract using the Order property on the DataMembers, we should be able to cope with simple property versioning issues (remember, we control all clients and can easily force-update them).
I keep hearing that we should use dedicated, transfer-only Data Transfer Objects (DTOs) over the wire.
Why? Is there still a reason to do so? We use the same domain model on the server side and client side, of course, prefilling collections, etc. only when deemed right and "necessary." Collection properties utilize the service locator principle and IoC to invoke either an NHibernate-based "service" to fetch data directly (on the server side), and a WCF "service" client on the client side to talk to the WCF server farm.
So - why do we need to use DTOs?
Having worked with both approaches (shared domain objects and DTOs) I'd say the big problem with shared domain objects is when you don't control all clients, but from my past experiences I'd usually use DTOs unless it development speed were of the essence.
If there's any chance that you won't always be in control of the clients then I'd definately recommend DTOs, because as soon as you share your domain objects with someone else's client application you start tying your internals to someone else's dev cycle.
I've also found DTOs useful when working in a versioned service environment, which allowed us to radically change the internals of our app but still accept calls to the old versions of our service interfaces.
Finally, if you have a lot of client applications it might also be beneficial to use DTOs as you're then protected with an easily versionable service.
In my experience DTOs are most useful for:
Strictly defining what will be sent over the wire and having a type specifically devoted to that definition.
Isolating the rest of your application, client and server, from future changes.
Interoperability with non-.Net systems. DTOs certainly aren't a requirement, but they make it easier to design "safe" types.
In your scenario these design features may not matter that much. I've used WCF with both strict DTOs and shared Domain Objects and in both scenarios it worked great. The only thing I noticed when sending Domain Objects over the wire was that I tended to send more data (and in unexpected ways) then I needed to. This was likely more due to my lack of experience with WCF than anything else; but it's something you should definitely be wary of should you choose to go that route.