I'm currently designing the foundation for a large application. We are going with the traditional 3 tier system using EF in the data layer, plain jane c# classes in the business layer and MVC / WCF for the ui layer. We have prototyped enough of the application to realize that this will work for us, however due to the complexity of the business requirements it will be common for some of the business components interact with one another.
Consider the following two business components:
RetailManager - Deal with everything related to retail in the system
CartManager - Deals with everything related to the shopping cart experience
The two interact, for instance, during the checkout process when an item is purchased. The inventory for the purchased item needs to be reduced.
Here is my thought process so far:
Let business components reference each other and ensure cyclical references never happen (CartManager references RetailManager, but never the other way). "Checkout" would be a method on the CartManager class, and it would call a method on the RetailManager to adjust inventory. While this will work, I'm not sure how well it will scale, and what the maintenance cost will be over time. It doesn't feel 100% "right" to me.
Create a Facade between the business components and the UI tier. In this example, the Facade would have the checkout method and a reference to both managers. I like this approach more than the first, however I know that not all of my business objects will need a Facade, and I don't want to create a ton of Facade classes just to have empty pass through methods.
I'm leaning towards 2, with the caveat that I will only create facade classes where needed. The UI tier will have access to both the Facade and the business layer components and will have to know when to use which (the only part I don't like about this solution).
I've done a lot of research but haven't been able to come to come up with a solution that feels completely right.
Any thoughts on using the facade pattern in this way, or other ideas to solve the problem are welcome.
Thanks in advance.
That's a typical problem for using manager/service classes. they always tend to get bloated. When you come to that point it's probably better to start using commands instead.
The great thing since you are using an IoC is that you doesn't have to refactor all the code directly, but can do it when there is time. Simply start writing commands for all new features while keeping the old architecture for everything else.
Here is a intro to commands: http://blog.gauffin.org/2012/10/writing-decoupled-and-scalable-applications-2/
And an intro to my own framework: http://blog.gauffin.org/2012/10/introducing-griffin-decoupled/
I would tend to go with facade implementation.
I would first ask myself, whose responsibility is it to make sure that inventory is reduced when a checkout happens? I don't think it is responsibility of CartManager to reduce the inventory. I would have a third class (in your case facade) that makes sure that whenever an item is checked out by CartManager, corresponding item is reduced from inventory.
Another option I would consider is event based implementation. CartManager would raise a ItemCheckedOut event whenever an item is checked out. RetailManager would subscribe to this event and would reduce the inventory whenever an event is raised. If you are new to event driven design, follow this question on quora - http://www.quora.com/What-are-some-good-resources-on-event-driven-software-design
I personally like the pattern of CQRS, it fits naturally with other architerural patterns
such as Event Sourcing and suited to complex domains.
Related
This might be a long list of questions but please bear with me. I started building LOB applications with WPF, PRISM, CODE FIRST and SQL CE, and after my first application (or attempt) I have many questions, so to begin with:
Where should business logic go, in the model or in a BLL layer just above the domain layer ?
Should view models receive references to repositories or should repositories be used only by the domain model objects ?
To put the second question in another way, what sort of objects should be given to view models ?
I use the same view model in display (in a data grid for example) and for editing in a form but that causes a lot of trouble, is there a better way to do this without code duplication ?
The biggest problem I have faced was that I always organized my view models in hierarchical relationships without allowing the children in the hierarchy to obtain references to their parents, and since the views bound to those children and invoked methods that caused the addition of objects to the repositories I couldn't find a way to notify the parents of the changes to the those repos. so the bound views could be updated, I have seen some people solve this using events but I don't like this solution and I would like to know if there is a better way to do it ?
Can anyone point to an example of building real life LOB applications using the technologies mentioned above, at least not examples that use VB .NET or WCF (I want local databases).
I'm developing a LOB app right now, with WPF, Entity Framework Code First and SQL CE 4.0 with a local database. I'm not using PRISM, but I'm using MEF as IoC with my own implementation.
So far, I recommend that you use the benefits of Code-First approach and implement as much business logic in your domain classes as possible. Also implement INPC in them. If you don't you'll end up having all your properties duplicated in your ViewModels, which is nonsense. There is no rule that says that the model should be dumb (although some people tend to think so), but a dumb model just makes the ViewModels more tedious to work with.
No clear recommendation here without knowing more of your project, but common sense: try to stick to best practices unless they start coming in your way. "Perfect" is often the enemy of "good".
Let the ViewModel get whatever they need (single model objects, collections, etc.) to serve your views. Often the simpler solution is easier to maintain in the long term.
I don't quite understand what you mean with this... I use my ViewModels several times if possible, but think that a ViewModel's function is to serve a View, if you are having trouble trying to get one VM to work for several Views, it's probable that you need to divide it into two different VM. Just gather all the common properties and methods in a base class and inherit from it as you need.
There are some loose-coupled ways for the VMs to communicate with each other. I'm using MVVM Light Messenger class for such things, but I understand that PRISM provides a similar functionality. It's not a sin to reference the parent from the child if you don't abuse it. I have a ViewModelBase<T> and the child have a reference for their parent pointing to the base class and specifying the T type, a good balance between hard and loose reference so far.
If someone points you to such an example, let me know! Actually, working with a local database should be simpler. In my case I'm using a singleton context (which a lot of people seem to loathe) but since this is a local app, with a single user and no threading complications a singleton context makes my life much easier. I'm still waiting to find a real good reason not to do so with this conditions.
PS: some people will probably downvote your question because... it is not ONE question, and it opens room for a lot of debate. If it gets closed, try the chat.
Hope this helps you, regards!
I've recently been handed a code base which does a few things I'm a little different to how I usually do them.
The main difference is that it seems to pass elements (say for example a drop down list control) down to the business logic layer (in this case a separate project but still in the same solution) where the binding to business data takes place.
My natural approach is always to surface the information that is required up to the UI and bind there.
I'm struggling to match the first technique to any of the standard patterns but that may be down to the actual implementation less than the idea of what it is doing.
Has anyone ever encountered this type of architecture before? If so can you explain the advantages?
The solution is an ASP.Net website. Thanks.
Thanks,
I would make the case that this is a bad architecture, since the original developer tightly coupled the business logic to the presentation layer. If you wanted to switch from webforms to, say, MVC, you'd have to refactor chunks of your business layer, which shouldn't be the case!
If it's at all possible, you should consider moving away from developing the site in this fashion. In the interim, you can at least start the decoupling process by splitting the logic up a little bit further. If, say, you have a BindDropDown(DropDownList ddl) method, split the method apart, so you have a GetDropDownData() method that returns your actual business object, and BindDropDown only sets the values of the DropDownList. That way, at least, you'll be more easily able to move away from the tight coupling of the presentation layer and business layer in the future.
Of course, if the site is already designed like that (with a clear demarcation between the presentation layer, the intermediate "presentation binding" layer, and the business layer), I could see a case being made that it's acceptable. It doesn't sound like that's the case, however.
No, you should not pass UI elements to the Domain Model to bind / Populate.
Your domain model should ideally be able to be used with Windows Forms / WPF / Silverlight / ASP.NET / MVC you name it.
Now, I kinda understand the idea that your business objects should know how to store and render themselves etc it's the OO holy grail, but in practice this doesn't work well, as there often are dependencies (database middleware, UI components etc) with those functions, that you do not want in your BO assembly, it severely limits your reusablility.
Something that you can do though that gives your users the illusion of your BO knowing how to render itself is using extension classes (in a separate assembly, to contain the dependencies) something like...
public static class AddressUIExtensions
{
public static void DisplayAddress(this Address add, AddressControl control)
{
...
}
}
Then the API user can simply do
var ctrl = new AddressControl();
address.DisplayAddress(ctrl);
but you still have physical separation.
Has anyone ever encountered this type of architecture before?
If so can you explain the advantages?
The only advantage is speed of development - in the short-term; so it's well suited to simple apps, proof-of-concepts (PoC), etc.
Implementing proper abstraction usually takes time and brings complexity. Most of the time that is what you really want, but sometimes an app might be built as a simple throw-away PoC.
In such cases it isn't so much that a room full of people sit down and debate architectures for a couple of hours and arrive at the decision that binding in the BL makes sense - it's usually a "whatever-gets-it-done-fastest" call by the developers based on speed.
Granted, that simple laziness or ignorance will probably be the reason why it's used in other cases.
Your business layer should return a model - view model that the UI layer will in turn use to populate what it needs - period. There should be nothing sent to the business layer in terms of ui components - period. Its that simple and that hard and fast of a rule.
If I have an app that consists of multiple layers, defined as multiple projects in a solution, is it ok to have a layer reference the layer directly above/below it? Or, should one use dependency injection to eliminate this need?
I am building on a more specific questions that I asked here, but I would like more general advice.
How would I go about setting up a project like this in VS2010? Would I need a third project to house the DI stuff?(I am using Ninject)
EDIT: example
Here is an example of my two layers. first layer has an IUnitOfWork Interface and the second layer has a class that implements said interface. Setup in this manner, the project will not build unless layer 2 has a references to layer 1. How can I avoid this? Or, should I not even be worried about references and leave it alone since the layers are adjacent to one another?
Layer 1
public interface IUnitOfWork
{
void Save();
}
Layer 2
public DataContext : IUnitOfWork
{
public void Save()
{
SaveChanged(); //...
}
}
General advise is to decouple layers by interfaces and use Dependency Injection and IoC containers for great level of flexibility whilst maintaining an Application.
But sometimes it could be an overkill for small applications, so to give you a more specific example you have to provide at least description of the application and layers which it has.
Regarding DI stuff, I would suggest to encapsulate it in a separate assembly.
See great article by Martin Fowler Inversion of Control Containers and the Dependency Injection pattern
EDIT: Answer to comments regarding interface
Only one way to get rid of such coupling is to store common interfaces/classes in a separate assembly. In your case create separate assembly and put here is IUnitOfWork interface.
EDIT: Ninject projects reference
There are 147 Ninject projects, I would suggest to download and investigate most interesting from your point of view: Ninject projects
This is a known "Tightly Coupled vs Loosely Coupled" dilemma and there is no general recommendation for it. It depends very much on how large are your component, how do they interact, how often are they changing, which teams do work on them, what are your build times.
My general advice would be keep balance. Do not go crazy by decoupling every mini class and on the other hand do not create a monolith where one small modification causes rebuild of the whole world.
Where change is expected, Favor loosely coupled components
Where stability is expected, Favor tightly coupled components
It is always a trade off:
There are costs associated with each decision:
The cost of having to make changes across tightly coupled components are well known.
-The change is invasive
-It may take a lot of work to determine everything in the dependency chain
-It's easy to miss dependencies
-It's difficult to insure quality
On the other hand, the costs of over-engineering are bad too
-code bloat
-complexity
-slower development
-difficult for new developers to become productive
To your example:
Take a look at Stoplight Example coming along with Microsoft Unity Application Blocks
People have already answered your question. I would suggest that the "below" layer should not reference the "above" layer as the below layer purpose is to provide certain functionality which is consumed by above layer and hence it should not know anything about above layer. Just like the nice layer model of TCP/IP stack
I am writing a web application which will include several parts - interactive calendar, todo list, managing finances,...
How should I design my solution? I thought something like this: each part has 3 projects (main project, DAL, BLL).
So in my case I would have 9 projects in my solution:
List item
Calendar
CalendarDAL
CalendarBLL
Todo
TodoDAL
TodoBLL
Money
MoneyDAL
MoneyBLL
Would this design be OK?
Also: where should web.config be? In it I have a connectionString which I would like to call from all DAL projects. Now I had web.config file in Calendar project and when I wanted to create dataAdapter in CalendarDAL with designer, I couldn't use existing connectionString from web.config.
Thanks
Unless you need to be able to separate and use the logic of this code in multiple applications, there is really no need to separate it into that many projects. It adds complexity but doesn't really add value. I used to separate the general BL library from the DL library but realized I wasn't really getting anything out of it...and I was making some things more annoying in the process. What is most important in separating code is the logical separation, not the physical separation into separate dlls.
Also, instead of breaking this up into separate web apps, put them in one. It will be a lot easier to develop and deploy. This allows you to use one web.config. If they are separate websites then create different web projects. If they are not, then don't.
[Edited]
One thing I meant to add, which is important, is this: The question of how you should design this is actually too general to really come up with a real answer. Those thoughts are just my general thoughts on project organization, which is what the question really seemed to revolve around.
In my opinion a good, layered .Net application architecture should have the following projects (structure) in the solution:
Presentation layer: Here's where the web.config resides, your ASPX pages and user controls (ascx)
Interface layer for the business logic layer: A layer containing exclusively interfaces of your business logic layer
The business logic layer classes: The classes implementing the interfaces of the interface layer (point above)
Interface layer for the data access logic: Again, exclusively interfaces of your data access layer
The data access layer classes: The same as for the business layer; the implementations of the interfaces of the layer before
This sounds quite complicated but represents a good separation of the logical layers. So for instance you could exchange your business logic layer or more probably (and realistically) your data access layer DLL without changing anything above since everything is separated by the according interface layers from each other.
To what regards the separation of the different projects you mentioned (i.e. Calendar, Todo, etc...) I'm not really sure. The question you have to pose is to whether these things are independent applications or whether they belong together. Modularization is important, but has to be thought of very well. What I for instance would separate is like when you have a project with different kind of UI's, one for the Administrator and one for the normal user. Here it could make sense to just exchange the presentation layer, the rest below could remain the same. So you could for instance put the admin presentation layer + the other logical layers below inside a solution and the user UI presentation layer + the (same) logical layers in another solution. This may make sense when different development teams are developing each of the solutions.
In your case it seems to me more of being a single project, so I would just group them internally in different user controls/namespaces, but not create a project (-> DLL) for each of them. This adds just complexity without any major advantage.
read up on MVC or nTier programming.
three basic layers:
your view: the aspx web pages
a controller: allows the view to interact with the model (kinda like encapsulation) it's just one class that acts as a go between.
a model: in here is your database/xmldata and your functionality. this is where the magic happens.
work in increments. first make the most basic of websites. then add functionality (one new feature at a time) , test it then move on.
Honestly this doesn't sound right at all.
You description of the components isn't really all that...descriptive (can you tell us what you're system does?), but it sounds to me like what you really have is 4 component classes (List, ToDo, Calendar, Money) in one project, one (always one) DAL project, and possibly a business logic project. Probably you'll require others. I can't think of any meaning of "DLL" which makes sense in this context.
Nine projects for four logical objects is way too much. Separate code projects by what is logically associated: less is more.
I'm not sure if I'm using "standard" terms, but this is a basic OO question I'm trying to resolve.
I'm coding a windows form. I don't want logic in the form event handler, so I just make a call to a custom object from there.
At the custom object, there are two sets of logic.
The "controller" logic, which decides what needs to get done and when.
The actual business logic that does what needs to be done (for example a control that performs a math operation and returns results, etc.).
My question is, does OO architecture allow for having both of these in a single object? Or is it recommended to split them out into a "controller" object and a "business logic" object? Is there a design pattern I should refer to for this?
For the time being, I've started down the route of combining them into one object. This object has a "start" method which contains the controller logic. This method then calls other methods of the object as needed, and ultimately returns results to the caller of the object.
What you're doing is a form of "fat controller" architecture. These days software development is trending toward thin controllers.
OO design is all about decoupling. If you internalize only one thing about OO programming, let it be that.
Check out "Domain-Driven Design Quickly." This free e-book is a condensed introduction to the concepts covered in Eric Evans' important book "Domain-Driven Design."
Getting educated in these concepts should help you to understand how to separate business logic from the controller, or service layer.
In general, you should probably have these in two different objects, but there's a qualifier on that. It may make sense, if your project is small enough and your object model is not complex enough, to have the functionality composed into one object; however, if your functionality is complex enough, it's almost certainly going to be better for you to segregate the controller and the business objects. At the very least, design the system with an eye towards separating the controller and the business objects at a later point, if you don't completely separate them now.
No, I don't put business logic in controllers. I add an intermediate service layer that's injected into controllers. Let the service do the work. Controllers are for routing requests and marshaling responses.
Putting the logic in a clean service layer is "service oriented", even if you aren't using web services or WSDL. It has the added benefit of still working if you decide to change controller/view technologies.
The answer to you design question can is as the following scenario: how would you design your application if you also had to provide a web-client for it.
Both your Windows Forms UI and you Web UI would be calling the same classes and methods. The only difference, then, would be how each populates the UI and communicates with the other layers.