Izrada jednostavne ASP.NET MVC aplikacije, dio 1: arhitektura
- Posted in:
- Quick thoughts
Zadnjih par godina sve više proučavam DDD (Domain driven development) način “razmišljanja” o razvoju aplikacija. Pristup problemu sa stajališta business eksperta i strukturiranje klasa i namespaceova, kao i upotreba različitih objektnih design patterna, tako da budu razumljivi vanjskom konzultantu i stručnjaku iz poslovne domene a ne samo programeru, mi zvuči logičnim i pravilnim. Moglo bi se reći da mi je standardno strukturiranje aplikacije na Sučelje (Interface) – poslovna logika (BLL) – pristup podacima (DAL), te isto takvo nazivlje varijabli i objekata počelo smetati (u nedostatku boljeg objašnjenja; nešto tu smrdi a nije moj overclockirani procesor). [more]
Razmišljajući o toj tematici, i kako da takav pristup primijenim u svojoj demo aplikaciji, pokušao sam sa vlastitim nahođenjem postaviti osnovnu infrastrukturu, ali to je ispalo dosta teško jer ja ipak gledam stvar sa čiste programerske perspektive. Takav način (poznat još kao i MSDN način pošto ga Microsoft često zagovara u svojim MSDN dokumentima i kao pravilni način izrade enterprise projekata) govori o objektima ovakvih naziva: DataAccessManager, ClassLibrary, DataSet, SqlRepository i sl. Ako pogledate ta imena, dali imate ikakvog pojma čemu služi pojedina klasa i objekt? Možemo zaključiti da DataSet sadrži nekakve podatke, ali koje, zašto, kako, to ne znamo. S druge strane. čitajući članke i knjige, u DDD perspektivi imamo domenski sloj, koji sadrži funkcionalnosti bitne za poslovni model. Zatim se spominje Service sloj, Application sloj, Infrastructure sloj, i da ne nabrajam dalje. Međutim, nije li to samo promijenjeno nazivlje ali isti onaj maloprije opisano pristup sa generalizacijom problematike iz programerske perspektive?
Zato prenosim ovdje cijeli jedan članak od Jeremy Skinnera, tvorca FluentValidation frameworka za validaciju (koji će biti također upotrjebljen u demo aplikaciji!), koji po mome sudu jako dobro objašnjava što DDD zagovara, i što se u biti krije iza tog imena:
I would not consider myself a DDD expert, but here are my thoughts:
1) The purpose of an Infrastructure project
I don't think the 'Infrastructure' project is the correct place for your entities/repositories. In a DDD architecture, the focus is obviously on the core business domain as represented by the various components of the system (entities, value objects, repositories, services etc). As such, I would suggest that the Entities should be part of your 'Domain' project as these are the core objects of your system. I would suggest that you reserve your Infrastructure project for classes that perform no specific business task, but are instead only assist in building the application structure (eg a base class that all your entities use, classes necessary for your Unit of Work implementation etc)
2) Namespace usage
The structure of your application is still very programmer-oriented. That is, you've grouped objects into namespaces that make sense to you as the developer, but probably won't make sense to the business expert. One of the core points of DDD is that there should be a ubiquitous language used by both the developer and the business expert to discuss the domain, and that language should manifest itself in the software. As such, rather than grouping your classes into namespaces like 'Entities' and 'Repositories', I would suggest that you instead group them by business area. For example, you might have an 'OrderProcessing' namespace which contains the Order entity (and any related value objects), an OrderRepository and an OrderProcessingService etc. This way your classes are grouped by domain function, rather than by an arbitrary definition that only makes sense to developers.
3) The 'Application' project seems superfluous and unnecessary
The 'Application' project seems like a mesh of classes that would be better suited to living in other projects:
3a) I think you need to make a distinction between the different types of services, ie 'Domain' services and 'Infrastructure' services. Domain services (eg an OrderProcessingService, or a TaxCalculationService) perform task that are core to the business, and as such should live in the Domain project in an appropriate namespace (see point #2). Services like a FileUploadService are not performing a business task, so they would probably best suited to live in an Infrastructure project.
3b) You mentioned that you were going to "Define new Entities that are more adapted to the Views" as part of the Application project. I don't really see the need for this. AccountLogin, AccountSignIn, AccountEditProfile etc all sound like they're View Models - not entities. Entities are a software representation of the core concepts of your domain, so in an order processing system these would be 'Customer', 'Order', 'Product' etc, but not AccountLogin. I would recommend that you think carefully about the purposes of these objects. What sort of logic does AccountLogin contain?
- If the logic is core to the domain, any only affects a single aggregate then it should be part of that aggregate. For example, if the 'User' object is the root of an aggregate containing 'User', 'Role' and 'Profile' then any logic that effects these classes should probably belong to the 'User' object. It would probably be a a good idea to have 'ChangePassword' or 'AddUserToRole' methods on the 'User' object than to have this in a separate class.
- If the logic touches *multiple* aggregates, then it should probably be in a separate Service. A contrived example: when a Customer pays for an Order, you want to 1) mark the order as successfully processed and 2) update the 'DateLastOrdered' property on the Customer. As this operation touches two different aggregate roots (an Order and a Customer), then it may be appropriate to put this in a separate service class.
- If the logic is only related to the UI and not to the domain, then that logic should be part of a View Model.
For example, what is the difference between 'AccountSignIn' and 'AccountSignInViewModel'? To me, it sounds like they should be the same, ie a projected representation of the User aggregate for the purposes of signining into the system via a login screen. This screams "View model!" to me :)
3c) Having view models is definitely a good idea, but I think it would be better to store them in the UI (Presentation) project as they're only going to be used by the UI.
I honestly don't think that FluentValidation is appropriate for validating Entities in a DDD scenario. Here's why:
As you know, FluentValidation works by validating the properties on an already populated object. It checks the value of each property to see if it is valid given a set of rules. This means that the object can exist in an invalid state until you perform validation. However, an entity should always be an accurate representation of a concept in your domain, and as such it should *never* exist in an invalid state. As such, you should build any necessary validation into your entities' properties. For example, if a Customer object has a Name property that is not allowed to be null, then you should put a null-check in the setter for the Name property. This way your entities cannot exist in an invalid state.
FluentValidation is far more suitable for validating your view models (in fact, this is what it was designed for). A view model is merely a representation of data sent to a view, or received back from a view. So let's say that you have a form for editing a customer's address. The values of this form could be posted back to your controller and deserialized into an AddressViewModel using a model binder. At this point, the AddressViewModel *could* be in an invalid state, so this is where FV comes in with a AddressViewModelValidator. If validation succeeds, you would then map the AddressViewModel back into the appropriate properties of your Customer object (either manually or by using something like automapper).
5) Unit of Work
My experience with the entity framework is limited, but I don't see why this shouldn't work with .NET 3.5 SP1. By its very definition, an ObjectContext *is* a unit of work. That is, it tracks the changes made to any entities within its scope and then you can either commit all the changes or discard them. In an ASP.NET MVC application, I would tend to have an ActionFilter that is applied to all of my controllers. At the start of the http request, the filter would create a new ObjectContext and store it in the HttpContext.Items collection. You would then use this same ObjectContext for any database operations in that take place during the current http request. At the end of the request, the action filter would submit any changes that have been made (but only if there are no validation errors).
As I said, I'm not a DDD expert, so these are just my opinions based on what (little) I know about DDD. If there's anything that doesn't make sense, or anything you want me to clarify, please let me know.
Cijeli thread rasprave možete pročitati ovdje
Slijedeći tjedan ću postaviti osnovnu strukturu projekta i opisati zadaću svakog njegovog dijela, naravno s pokušajem primjene DDD načela. Također, trebao bi napraviti jedan mindmap svih featura, da bi odabrali one bitne za dobiti prvu verziju web sitea, i prema odabranima featurima formirati taskove. Svaki task ne bi smio trajati vise od par radnih sati, ipak se tu radi o relativno malenom projektu.
Nakon svake iteracije izvršenih taskova po jedna od funkcionalnosti web-a bi trebala biti napravljena i odmah vidljiva – znači ne raditi cijeli data access layer, pa onda cijeli interface, itd. Tim načinom bi prve rezultate vidjeli tek kada bi natipkali 80% html i c# koda. Ovakvim agilnim pristupom ćemo puno prije vidjeti rezultate, i lakše intervenirati kasnije kada uvidimo određene probleme i zamjerke (lakši refactoring).
Također, koliko god budem mogao pisati ću i Unit Testove, iako za sada neću ići sa red-green test-first pristupom (prvo pisanje testova koji ne prolaze, potom pisanje koda i testovi prolaze)
DDD je sigurno najjaca stvar u zadnjih nekoliko godina... Sto se tice arhitekture mozes pogledati malo oko Onion Architecture..Edin
My boss just yelled at me cause i didn't do it right just a few moments ago. I'm trying to wrap my mind around this and find an easy solution out but i guess i'll have to outsource it in the end cause i'm just to early now. Well watever, there has to be something to work...internet chat rooms
I would like to know the blogging platform that you are using. It looks simple . Are you running blogspot or blogster?Coffee Flavors
Hey very nice blog!! Man .. Beautiful .. Amazing .. :[:p] :[I will bookmark your blog and take the feedsdiscount designer handbags
Thanks for this brilliant article. I am delighted after reading this. Thank you!mississauga real estate agents
Good post, liked the idea, keep up the good work!cheap new laptops
This is very good content about condo, I admire what you have done here, as well as share great stuff with good ideas and concepts, I'm truly pleased to post my comment on this weblog, numerous thanks to the author.Condos
How to manage Nausea during Chemotherapy: Eat small means throughout the day. Do not eat fatty foods before or during treatment and rest after eating (but do not lay completely flat). Avoid strong scents or odors that might cause nausea. Talk to your doctor about nausea, they may be able to prescribe you something for the nausea. No smoking tobacco because it can upset the stomach.Marilyn Robinson’s Headwear
Wow, Awesome post - hudo's vibe - Izrada jednostavne ASP.NET MVC aplikacije, dio 1: arhitektura was a great read. I'm such a newbie when it comes to all this, Thanks for this!Kimbra Marciel
Your web site is very much worthy of a bookmark. Thank you for the terrific and cool post!glass etching cream
Located a awesome advocacy group called Freedom Disability. They can assist you to apply for and win disabilitywith the SSA.Apply For Disability
Hey man, hahah ...what has come about??l your website is pretty unsightly in my mobile internet browser! But I am adoring the content so great work. In addition, you are able to get <a href="http://www.clubseo.net">free web site design</a> at ClubSEO.net. It's a really good option to get your principal web site more visible as well! Check it out if you have one minute. I did a couple of sites there and just pointed them all back to my blog and I get tons of new relevant subscribers now. Anyway, thank you for the shizzle dude. Have a great summer and stuff! :DTracey Roxberry
Wow! What a concept! Stunning .. Amazingnetbook sale
Thank you for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If probable, as you gain expertise, would you brain updating your web site with even more material? It can be extremely beneficial for me. Rapidshare search web pagesMurano glass chandelier
I don’t agree with most guys here; since I started reading this post I couldn't stop until , while it wasn't just what I had been trying to find, was indeed a fantastic read though. I will immediately get your blog feed to maintain informed of any updates.internet income
TY.Hotel In Romford
This is a nice website!, i just recently found it and now is on my Bookmark.Job - MexicoFishingDeals
Keep the effort of keeping this Website updated, and if you have a chance please visit my site http://www.mexicofishingdeals.com
thanks and keep tight lines.
That i like this post.Houses To Rent In Romford
Can you do another post but compare it to the primary source? Awesome way to approach it, but perhaps I just haven't thought of it that way.Trademark Logo
if you do good you pay, I had small house in Virgo they where wheat as vagggine on a poleDalek
if you do good you pay, We have big house in Virgo they are wheat as birrd on a polecokrew
wow this post has got a lot of commentsTora Gharing
I wish you had a rating metric for your post, because I would definitely give you a 5 out of 5 -- perhaps you should implement that to have readers rate your posts, etc.insurance
dvrmcrtpcevlfeqsotwc, http://kathyvanzeeland.org kathy van zeeland, BLvmnOm. jlhrqgbesadvepuhatvb, http://stearnsandfoster.org stearns and foster, RDUvIwR.kathy van zeeland
You raise many questions in my head. you wrote a good post, but it is also mind provoking, and I will have to think about it some more I will return soon. All in all... this is what I was looking for. Bravo!Webmaster Forum
Cool blog! I dont think Ive seen all the angles of this subject the way youve cleared them out. Youre a true star, a rock star man. Youve got so much to say and have a lot of knowledge about the subject that I think you should just teach a class about it...HaHa!goyard bags
Great Post, thanks for this great Post. I will come back soon _Barton Dunny
Thanks for the Post, thanks for this useful Post. I will come back later .mikrojobs
Thanks for the Post, thanks for this great Post. I will come back soon _microjobs
Good day! Do you know if they make any plugins to safeguard against hackers? I'm kinda paranoid about losing everything I've worked hard on. Any suggestions?applesaucemaker
As you get elderly, your current males health problems will probably switch. May a light beer instinct result in health conditions?erectile dysfunction
I've been browsing online more than three hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my view, if all webmasters and bloggers made good content as you did, the net will be much more useful than ever before.Lastminute Mallorca
21. Pretty section of content. I just stumbled upon your site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Anyway I’ll be subscribing to your augment and even I achievement you access consistently rapidly.strony www
Hello friend I appreciate you for discussing this short article around. Generally i wouldn\'t inquire into Blogs. But i such as this one. I wish additional articles or blog posts as well as written content on-line could well be about very helpful along with informative as compared to this place. Wonderful article, thanks Sincerely.SEO Tipps
hello, I haven't spoke to you on the chat in a while, but I guessed I would probably email you from my all new Netbook!! No joke, I work for a top company these days in the fraud dep. Never tell everyone but we uncovered this site that is thoroughly glitching and submitting out free of charge Android !! to any person that signs up. I suppose you will probably have to confirm your e mail, Best wishes amateurpornoamateurporno
Thanks for sharing you personal and a glorious informationArdelle Hilty
awsome post, thanks for your insights.Michael
I do like the manner in wich you have framed this specific concernuser3
please visit king-craft.tk !
Visit my Server:King Craft
thanx and nice informationsda3mfny.com
<a href="http://da3mfny.com" title="دعم فنى">دعم فنى</a>
Have a light but fulfilling breakfast. Campbell is the only guaranteed way to assure that you have. We look forward to meeting in person to the facility for neonatal nurse organizations a set amount of time for those late-night rehearsals, weekend run throughs, and cast parties! In these classes many students neonatal nurse organizations do not know when it was not the issue anymore, fear was.differenttypesofnurses.info
Here is my web-site ... enrolled nurse traineeship - differenttypesofnurses.info ( differenttypesofnurses.info - http://differenttypesofnurses.info/ )
It is not only the tutor's effort but equal participation from the student that would make us all laugh. You must have a documented settlement agreement with whatever department is responsible. If you are not too limited and the pain is kept enrolled nurse jobs adelaide - enrollednurse.info under control. If you are looking for free CNA training classes in the degree programs that will prepare enrolled nurse jobs adelaide - enrollednurse.info you for interviews. However, there are only, maximum three attempts for taking the stand. It is simply a part of.Enrollednurse.Info
Also visit my website Nursing Schools In North Carolina ( Enrollednurse.Info - http://enrollednurse.info/ )
There are so many things that you can use for younger skin. Last but not the least, you must have a group of pageant directors. While trying to strike out a balance, girls tend to go overboard with bright and bold colors that mar their natural beauty tipps ( Katlyn - http://preciouspadgett.tblog.com/post/1970542008 ). With the greater perspective to turn a niche market into a global phenomenon, BGI has offered a remarkable dimension to the idea of growing bougainvillea plant. During winter season, you can create a unique and attractive effect in the salons.Katlyn
The architectural model has been, since its inception on of the most popular when it comes to the various beauty tipps uses of potato today.http://highmeadows.us/userinfo.php?uid=58877
My web blog: http://technorati.com/people/RosemarieW/ [ http://highmeadows.us/userinfo.php?uid=58877 - http://highmeadows.us/userinfo.php?uid=58877 ]
It's hard to find educated people for this subject, however, you seem like you know what you're talking about! ThanksRead Even more
Also visit my webpage; Read Even more - www.waterhealth.com/simple-strategies-you-could-apply-internet-marketing
It's an remarkable post designed for all the web users; they will obtain advantage from it I am sure.Mosesnhmx.sosblogs.com
My blog :: tmobile business ( Mosesnhmx.sosblogs.com - http://Mosesnhmx.sosblogs.com/ )