I'm having problems to understand the conception of DDD. I have an ASP.NET project with this structure:
ASP.NET MVC4 project: xxx.UI.Web
Class Library project: xxx.Application xxx.Domain xxx.Infra.EF
I'm trying to keep this relation:
xxx.UI.Web only have relation with xxx.Domain and xxx.Application
xxx.Domain doesn't have relations.
xxx.Application have relation with xxx.Domain and xxx.Infra.EF
xxx.Infra.EF have relation with xxx.Domain
But now I'm having many problems to keep this concepts with Entity Framework. I have created the Entity repositories in the xxx.Infra.EF and created a generic repository (with interfaces and so on) in xxx.Application.
The problems begin when I need to pass a personalized Entity context to my repositories, because I use the repositories in the xxx.UI.Web and I can't instantiate a new Entity context because It will broke my project pattern (The Entity context comes from xxx.Infra.EF).
My idea is to create many helper methods that will process this kind of operations for my xxx.UI.Web, and I wouldn't like to create this methods in xxx.Application (It looks a little strange to create many methods with a little relation with my business logic).
So I was reading a little about Domain Driven Development (DDD) and I knew about the Service layer, and I think It seems to be the layer that was created to solve problems like this, or not?
My idea is to create a new class library project called xxx.Service and make this project keep relation with xxx.Domain and xxx.Infra.EF. Is It right? I know that I could search for another solutions for my case with Entity context, but I guess I'll have more problems like this in the future with other things, so I tried to find solutions for It. I should study much more about It, but I think I could identify the solution for my problem.
I suggest you further study the concept of layered architecture.
You are correct that the Domain should not reference other layers, such as the Presentation Layer and Infrastructure Layer.
The most common style of layered architecture is the "Onion Architecture". See image and link below.
http://jeffreypalermo.com/blog/the-onion-architecture-part-1/
The Service Layer
You are also correct that a new layer (Service Layer) will solve your problem. You see, the problem arises because the UI/Presentation Layer is talking directly to the repositories(Infrastructure).
In our approach, the Presentation Layer does not communicate directly with the Infrastructure and Domain. We have a Service layer that comes between the Presentation and the Domain.
The above architecture borrows heavily from the Onion Architecture. We don't have domain services. Application Core is our CrossCutting Layer.
People often misunderstand the point of a multi-tiered application. The goal is not necessarily to remove dependencies, but rather to encapsulate and modularize code. Your MVC frontend shouldn't need to be concerned with your entities and how their queried, added, updated, etc., but it doesn't mean it doesn't need access to them. Long and short, don't focus on project references, but rather factoring out code that is not in each project's "domain" into a more appropriate "domain".
To that end, it's not really possible to say based on the information you provided exactly what you should do. The question is opinionated to begin with and will very likely end up being closed as a result. Ultimately, you have to decide what's best for your project. Do what makes sense, rather than blindly following some pattern. After all, patterns are supposed to just be a codification of common sense approaches to common problems, anyways.
As a novice to this realm, I am planning on building an mvc application. I had originally started a web forms application but decided the scalability and testability will benefit more with an mvc application. I chose to switch with the added benefit of being easier to add more features later on (instead of having code baked into web forms pages).
Now a little about my application, it is an application to stimulate an RPG class builder and moveset. In all simplicity, users can register for a class, and depending on other skills they can register for, they can see a custom move set based on these categories. The way I am envisioning it is I will be able to go back and add more classes and skills later in the database and have users register for this new content immediately once it has been added to the project.
Everything lives in normalized tables, so many joint tables do exist. For each new skill or class I add will mean a handful of tables will be added to the database. This speaks to the way the data will be stored, everything and all information about classes, user data, skills, etc will be stored in the database.
I have designed all the initial database tables I will need to have at the start, and functionality I need (a home page, view skills page, view move sets page, etc.). I am stuck at the next step; where do I go? Should I make my controllers first? Models? Views? Design my page layouts? I am asking for advice from people who have taken a similar organic approach to an mvc project. I am facing analysis paralysis on what to start on, knowing I have a lot of work ahead of me.
Thank you for taking your time to answer.
I've taken everyone's advise and am putting together a website to learn MVC: http://learnaspnetmvc.azurewebsites.net
The most important advice I can give you: just start. A big project can seem overwhelming, especially when you're looking at it like a big project. Instead, break it into small achievable tasks. Find something you can do right now, the ever-so-smallest subset of functionality, and do it. Then do the next one. And the next.
That said, I'll tell you my personal process. When I start on a new application or piece of an application, I first like to create my models. That way I can play with the interactions between them, flesh out the relationships, and think about the needs of my application in a somewhat low-pressure, easily disposable way. I also use code-first, whereas you've gone an created your database tables already. Some people prefer to do it that way. Personally, I find starting with my classes and letting those translate into an underlying data store much more organic. In a sense, it relegates the database to almost a non-existent layer. I don't have to think about what datatype things need to be, what should be indexed and what shouldn't, how querying will work, what kind of stored procedures I need, etc. Those questions have their time and place -- the nascent development stage is not that time and place. You want to give your brain a place to play with ideas, and classes are a cheap and low-friction medium. If an idea doesn't work out, throw the class away and create a new one.
Once I have my models, I like to hit my controllers next. This lets me start to see my models in action. I can play around with the actual flow of my application and see how my classes actually work. I can then make changes to my models where necessary, add additional functionality, etc. I can also start playing around with view models, and figuring out what data should or should not be passed to the view, how it will need to be displayed (will I need a drop down list for that? etc.), and such. This, then, naturally leads me into my views. Again, I'm testing my thinking. With each new layer, I'm hardening the previous by getting a better and better look at how it's working.
Each stage of this process is very liquid. Once I start working on my controllers, I will make changes to my models. Once I hit the views, the controllers will need to be adjusted and perhaps the models as well. You have to give yourself the freedom to screw up. Inevitably, you'll forget something, or design something in a bone-headed way, that you'll only see once you get deeper in. Again, that's the beauty of code-first. Up to this point, I don't even have a database, so any change I make is no big deal. I could completely destroy everything I have and go in a totally different way and I don't have to worry about altering tables, migrating data, etc.
Now, by this point my models are pretty static, and that's when I do my database creation and initial migration. Although, even now, really, only because it's required before I can actually fire this up in a browser to see my views in action. You can always do a migration later, but once you're working with something concrete, the friction starts to increase.
I'll tend to do some tweaking to my controllers and obviously my views, now that I'm seeing them live. Once I'm happy with everything, then I start looking at optimization and refactoring -- How can I make the code more effective? More readable? More efficient? I'll use a tool like Glimpse to look at my queries, render time, etc., and then make decisions about things like stored procedures and such.
Then, it's just a lot of rinse and repeat. Notice that it's all very piecemeal. I'm not building an application; I'm building a class, and then another class, and then some HTML, etc. You focus on just that next piece, that small chunk you need to move on to the next thing, and it's much less overwhelming. So, just as I began, I'll close the same: just start. Writers have a saying that the hardest thing is the first sentence. It's not because the first sentence is really that difficult; it's because once you get that, then you write the second sentence, and the third, and before you know it, you've got pages of writing. The hardest part is in the starting. Everything flows from there.
The other answers here have great advice and important nuggets of information, but I think they do you a disservice at this stage. I'm the first to advocate best practice, proper layering of your applications, etc. But, ultimately, a complete app that follows none of this is more valuable than an incomplete app that incorporates it all. Thankfully, we're working with a malleable medium -- digital text -- and not stone. You can always change things, improve things later. You can go back and separate your app out into the proper layers, create the repositories and services and other abstractions, add in the inversion of control and dependency injection, etc. Those of us who have been doing this awhile do that stuff from the start, but that's because we've been doing this awhile. We know how to do that stuff -- a lot of times we already have classes and libraries we drop in for that stuff. For someone just starting off, or for an app in its earliest nascent stage, it can be crippling, though. Instead of just developing your app, you end up spending days or weeks pouring through recommendations, practices, libraries, etc. trying to get a handle on it all, and by the end you have nothing really to show for it. Don't worry about doing things right and do something. Then, refactor until it's right.
As a first step in planning a MVC framework application, We should start with a strong Model (typical C# props). This process is going to take most of our time, based on the fact that we need to understand the business first and then the relationships between different workflows and entities. So times business models evolve as time passes. So spend qualitative time on building this layer, but not too much.
Once domain (Business) Models are ready, before we actually start coding for Repository classes, we should define our Repository Contracts which are typically Interfaces. Contracts help all parties(other components) to interact with each other in the exact same way. Then we implement contracts on the Repository component, which is just going to act like PUSH and PULL data from your persistent medium (say database). Remember repository component never going to have any idea on business logic.
Once backend has been established, We can concentrate on my actual business process implementation. We can define one more level of Contract which defines all business operations which are to be done using Model classes. This interface has been implemented by BusinessLogic Component which does the core business activity (specific methods for every business operation). This particular component will use Repository component to delegate business data to persistence medium.
With above step completed, We can easily go and build Controllers. We should be calling business logic component methods in controllers and get work done. Once controllers are done, we can define our views and other UI elements like partial views etc.
Pictorial representation of the flow is as follows -
A simple architecture (from high to low level)
Presentation Layer
Domain Logic Layer
Data Access Layer
Database
Presentation layer is MVC project containing Views, Controllers and optional View-Models.
Domain Logic Layer is Class Library project which Presentation layer will access (via DLL or Service reference). This layer contains business logic and rules for the application.
Data Access Layer may contain two sub-layers-
Repository. User repository is best practice for any long term application.
Entity Framework Model.
This will communicate with database.
Database you already have.
I would suggest reading through a book by Scott Millet, called Professional ASP.NET Design Patterns.
ISBN : 0-470292-78-4
Scott walks through what a good ASP.NET site should look like from an architectural standpoint - i.e. DataAccess layers, Business Logic layers, Presentation Layers, Domain events etc.
By following on from industry standards, you will gain a better knowledge of how to correctly put together an MVC web-site.
Hope this helps.
I would suggest you to make your MVC application around a ASP.NET Web API , since it will help, in case you go for a mobile application later.
Since you are a MVC newbie, you should download some open source projects on MVC shared by seniors in the community. Study two or three projects, and analyze a solution which will the best for you.
A quick googling will get you to some good projects.
e.g.
Making a simple application , Prodinner
After that you should also go through MSDN tutorial on MVC 5 app with SSO , to enable social logins.
Can you advice on structering the solution projects, files, fodlers in a way that it matches with the MVP design pattern in order to represent the pattern idea?
I mean how would you put your presenters, data acces layer, views etc.
Thanks
Solution architectures are generally pretty independent of which UI architecture you're using, although you might have some additional separation if you plan to have multiple UI applications (most projects don't).
I tend to start out with a template similar to this:
Acme.Sales or Acme.Sales.Core - internal domain/business logic
Acme.Sales.Entities - data entities used for persistence layers. Entities have similar class structure to the core (domain) model, but tend to have thinner logic, additional properties like Id, two-way relationships (as opposed to the one-way relationships in the domain model), and virtual members for the ORM to be able to override. This assembly will also normally include abstract repositories for CRUD operations on entities.
Acme.Sales.Entities.Impl where Impl is something like LinqToSql or NHibernate - this namespace defines one possible implementation for actually persisting the Entities. Concrete implementations of the abstract repositories go here.
Acme.Sales.UI contains common classes relating to any user interface - might be an MVP GUI or even a CLI. As with Entities, these are similar to the Core classes but tend to have presentation-specific logic and attributes, such as validation and formatting (which most often today is done through DataAnnotations). Note that the core library should also validate, but UI validation tends to be more about formatting and sanitization of inputs than business rules. It's tempting to mimic the domain's class structure here, but you'll have an easier time overall if you stick to flat, DTO-style classes for your UI model.
Acme.Sales.UI.Services contains abstract or concrete "service" types that are meant to interact with both the UI and the domain/persistence layers. Thus this project takes dependencies on Acme.Sales (domain), Acme.Sales.Entities (abstract repositories), as well as Acme.Sales.UI, and handles all of the mapping activities between those different layers.
Acme.Sales.UI.Impl where Impl here is something like Mvp, Mvc,Mvvm, and so on. You can drop the UI from this namespace if you want, as the implementation implies what it is. This generally takes a dependency on the UI project but adds those things specific to a particular UI model; controllers, presenters, view-models, etc. This is your actual "application". It's also where you normally choose an IoC container (AutoFac, Ninject, Spring.NET, Castle, Unity) and wire up all the specific implementations to the abstract types.
Within your application project you'd want to separate logical concepts into different sub-namespaces/folders. For example put your presenters in Presenters and views in Views - pretty straightforward - and create subdirectories in each of those if you start getting a really huge number of screens (e.g. Views.Billing and Views.Shipping). It's also OK to create top-level Area directories/namespaces here and put separate Presenters, Views, etc. in each one of those areas - this is the approach currently taken in ASP.NET MVC.
You don't need to separate Presenters and Views into different projects. Rest assured that the views which you tailor-made for MVP will be utterly useless for MVC or MVVM, and vice versa. The only part of a model-driven app that really stands a chance of being reused is the model itself.
Note that this is just a very basic architecture for an app with a single database and relatively simple domain logic. It doesn't include any higher-level back-end constructs like app integration (e.g. web services), eventing (pub/sub), batch processing, CQS, ad-hoc reporting, and so on and so forth. These tend to be pretty common in larger-scale business apps but if you're just starting out on a new social bookmarking app then you don't need any of that complexity.
Also note: This is all assuming you're planning at least a medium-size project - let's say one that you and/or your team will be working on for 6 months or more. If you plan to bang it all out in 1 month or less then please, don't waste your time on solution architectures at all. It's perfectly OK to just jam it all into one project and reuse the same classes for domain, entities, and UI - as long as the project is small enough to be easily understood and maintained. Carefully monitor the complexity and maintenance overhead and consider refactoring into the above structure over a longer period of time if the project starts turning into a ball of mud.
Below would be a nice start. You could split up even more if the project gets bigger:
Company.Project.Core -> Controller logic
Company.Project.Domain -> Domain models (view models and database models)
Company.Project.Interface -> Views, presenters
I'm working on a fairly large project at the moment and am currently in the planning stages. I've done a lot of reading into the various patterns suggested for development, somthing that has split the team at the moment is when using Entity Framework should the classes be passed through the applciation layers so that a view accepts an Entity Framework class or should these classes be mapped to BLL Classes and if so at which point (Controller or Library) should this be done?
I'm interested in hearing some positives and negitives for each solutions.
This is one of those great "it depends" questions ....
For me it's a matter of pragmatism. I use the raw entity classes where ever I can for expediency. I start using DTOs when either the object graph in question starts becoming too cumbersome or the object in question has sensitive data I don't want sent over the wire.
This is again one of those questions that doesn't really have a right or wrong answer, its personal taste really. Personally I would opt for using DTO's or interfaces when passing data to the Views. I don't tend to pass around entity objects to different layers of my application they are strictly confined to the DAL, or if I do need to pass it up a layer I would almost always use an interface never the concrete type.
I work for a firm that provides certain types of financial consulting services in most states in the US. We currently have a fairly straightforward CRUD application that manages clients and information about assets and services we perform for each. It only concerns itself with the fundamental data points and processes that are common to all locations--the least common denominator.
Now we want to implement support for tracking disparate data points and processes that vary from state to state while preserving the core nationally-oriented system. Like this:
(source: flickr.com)
The stack I'm working with is ASP.Net and SQL Server 2008. The national application is a fairly straightforward web forms thing. Its data access layer is a repository wrapper around LINQ to SQL entities and datacontext. There is little business logic beyond CRUD operations currently, but there would be more as the complexities of each state were introduced.
So, how to impelement the satellite pieces...
Just start glomming on the functionality and pursue a big ball of mud
Build a series of satellite apps that re-use the data-access layer but are otherwise stand-alone
Invest (money and/or time) in a rules engine (a la Windows Workflow) and isolate the unique bits for each state as separate rule-sets
Invest (time) in a plugin framework a la MEF and implement each state's functionality as a plugin
Something else
The ideal user experience would appear as a single application that seamlessly adapts its presentation and processes to whatever location the user is working with. This is particularly useful because some users work with assets in multiple states. So there is a strike against number two.
I have no experience with MEF or WF so my question in large part is whether or not mine is even the type of problem either is intended to address. They both kinda sound like it based on the hype, but could turn out to be a square peg for a round hole.
In all cases each state introduces new data points, not just new processes, so I would imagine the data access layer would grow to accommodate the addition of new tables and columns, but I'm all for alternatives to that as well.
Edit: I tried to think of some examples I could share. One might be that in one state we submit certain legal filings involving client assets. The filing has attributes and workflow that are different from other states that may require similar filings, and the assets involved may have quite different attributes. Other states may not have comparable filings at all, still others may have a series of escalating filings that require knowledge of additional related entities unique to that state.
Start with the Strategy design pattern, which basically allows you outline a "placeholder", to be replaced by concrete classes at runtime.
You'll have to sketch out a clear interface between the core app and the "plugins", and you have each strategy implement that. Then, at runtime, when you know which state the user is working on, you can instantiate the appropriate state strategy class (perhaps using a factory method), and call the generic methods on that, e.g. something like
IStateStrategy stateStrategy = StateSelector.GetStateStrategy("TX"); //State id from db, of course...
stateStrategy.Process(nationalData);
Of course, each of these strategies should use the existing data layer, etc.
The (apparent) downside with this solution, is just that you'll be hardcoding the rules for each state, and you cannot transparently add new rules (or new states) without changing the code. Don't be fooled, that's not a bad thing - your business logic should be implemented in code, even if its dependent on runtime data.
Just a thought: whatever you do, completely code 3 states first (with 2 you're still tempted to repeat identical code, with more it's too time-consuming if you decide to change the design).
I must admit I'm completely ignorant about rules or WF. But wouldn't it be possible to just have one big stupid ASP.Net include file with instructions for states separated from main logic without any additional language/program?
Edit: Or is it just the fact that each state has quote a lot a completely different functionality, not just some bits?