Im starting a new application in WPF and I want it to have a good architecture so that it can be maintainable. Im using Entity Framework and what I planned so far is.
• View Layer: One project (startup) with the startup view, and main menus. Different projects for each type of view, for example, if I have views related with Books then I'd have a project named BooksView with all the views.
• Business Layer: One project for each type of Business Class, for example BusinessBooks. Each one would have a Repository with the specific operations and any helpers to do calculations if needed.
• Data Acess Layer: It contains a folder named Entity Framework with the DBContext and with the T4 generated classes and with a class named ContextCreator which has the following code:
public class ContextCreator : IDisposable
{
private MesaOperativaDB context;
public ContextCreator()
{
context = new MesaOperativaDB();
}
public MesaOperativaDB getContext()
{
return context;
}
public void Dispose()
{
context.Dispose();
}
}
Then a view would use the static repository of any project of the Business Layer that needs, and this repository would use the class above to get the DBContext and use it like this:
public static List<Novedades> GetNovedades()
{
using (ContextCreator db = new ContextCreator())
{
IQueryable<Novedades> novedades = db.getContext().Set<Novedades>().AsQueryable();
return novedades.ToList();
}
}
Is this approach any good?
Thank you in advance guys.
Though I am quite not sure of your application scale but it seems good to me that you have started on a right path for separation of concerns.
But you may need to rethink if creating separate project for each category of views does not introduce unnecessary complexity.
Again I am not sure if you are new to WPF, but for the View layer for better maintainability, loose coupling and hence testability etc., MVVM is the best chosen pattern to organize things in place.
For getting MVVM in place you may handcode everything from scratch or there are nice frameworks available like:
MVVM Lite
Assisticant
Also if you are planning towards a relatively big(layman term!!)/enterprise class application and since you are looking for highly maintainable, flexible application you may consider using PRISM framework from Microsoft. Prism Guidance and downloadable PDFs etc.
Once you finalized on the View part, the you need to focus on Validations for your app and whether you would be implementing validations in the ViewModel or in your domain objects. Assisticant framework has some good domain-centric validation mechanism built into it.
For the Data access layer, since you chose to go with EF, from my understanding so far, the Unit-Of-Work with Repository pattern would greatly help you to gain extensibility, testability etc. features.
If you are planning high on unit testability and loose coupling of your application, you need to consider Inversion of Control and Dependency Injection perhaps with a suitable framework.
Here you can check a WPF application framework to understand on how to organize different areas of a WPF application in a layered approach.
Hope this may help you to dig further.
Related
I have a plan to rework my company web publishing platform with dependency injection because the coding references start to become a bit more complex.
In my research I have found a lot of examples regarding MVC but our intention at the moment is to rework the web platform's Business logic, DAL, Core etc.. with minimal UI interventions.
The architecture of the web platform is the following
SQL database
DAL (EF6)
Separated model from dal (poco)
Business Logic
CMS System
Front end (websites)
All in all separated projects with their own concerns but heavily referenced in between.
In my research to counteract heavy referencing and coupling I have chosen and followed the following example
techbrij blog post
I do understand the concepts of abstraction and dependency injection well and have set up a test project but hit a snag.
In MVC the instantiating new data class (poco) is handled by the ActionResult
// POST: /Country/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Country country)
{
// TODO: Add insert logic here
if (ModelState.IsValid)
{
_CountryService.Create(country);
return RedirectToAction("Index");
}
return View(country);
}
so far so good if we use MVC. But if I use Webforms in order to insert new record my logic says that i need to instantiate a new class from the model fill its properties with specific values and pass it to the BLL/DAL or service layer:
public void InsertRecord()
{
Country country = new Country();
country.Name = "Some Country"; // or value from textbox..
_CountryService.Create(country);
}
My question is:
Regarding webforms, is this OK or do I need to absrtact the model in order to inject the new data class without the "new" keyword
Since using the "new" keyword will not decouple my data model, how would you do this to achieve decoupling/ioc/di?
I think that's fine. All the MVC framework is doing is newing up an instance of Country and matching up request parameters to your model's properties. You might find a library that does the same in webforms but it would probably be overkill.
You could use a factory to abstract away the newing up but it's probably not for situations like you have here.
Take a look at this article. It differentiates between Injectables and Newables.
In my understanding, Injectables are classes that present behavior that you want to vary using DI. While Newables are simple classes that mostly contain data. They might contain some behavior that is internal to these classes (does not require external services to work) so you don't want to change such behavior using DI.
It seems to me that the Country class is a Newable. Therefore, it is perfectly normal to new it up via new.
The link you provided use repository pattern, I personally run away from it because it is all about hide your persistence tools, and if you hide your arsenal you lose the power it provides, apart from the probably unnecessary added complexity.
That said it is ok to manually create entities with new keywords, as long as you don't do it in the user interface class, for web forms you can use Model View Presenter combined with modern Model Binding technics available for Asp.NET Web Forms. Presenter instantiate entities and interacts with persistent mechanisms (EF in your case).
You can decouple UI code from presentation code, presenter can lives in its own assembly and works with View Interfaces so you will inject concrete implementations with IoC.
Here is a very basic sample skeleton for a sample infrastructure representing the above:
public interface IView{}
public abstract Presenter<T> where T : IView
{
public Presenter( T view){ View = view;}
public T View {get;set;}
}
The services I build are about encapsulating Business Logic, Application Logic, etc. Again, you will want have to avoid hard references to concrete implementations of those services by working with interfaces and injecting concrete implementations with some IoC.
I want to decouple the domain logic entirely from the persistence layer in my next project. However, I am reading conflicting reports as to the optimal approach.
Basically the gist I am getting is forget trying to implement a generic repository and classic UOW as Entity Framework 5 and above are already built on UOW and repository pattern. Doing so would complicate the application and not provide any genuine isolation from entity framework.
Rather, just abstract the context away with an application layer interface and employ some solution to map domain/view models to their respective entity classes before passing them to the context for saving.
I saw some short, incomplete extracts on how to do this here and there, but I would ideally want to be able to get my hands on a simple, well made project (pref WebAPI oriented) that makes use of all the approaches discussed above. In general I don't know of any good boilerplate resource for .NET stuff, other than the projects on asp.net and they seem to be far too simplistic and not adopting the conventions you'd find in practice.
Mainly used this post as source.
It may be good to check my article: http://www.codeproject.com/Articles/768664/Introduction-to-ASP-NET-Boilerplate
ASP.NET Boilerplate is a starting point for new modern web applications using best practices and most popular tools. It's aimed to be a solid model, a general-purpose application framework and a project template.
Using ABP, you will have a good infrastructure to implement layered, domain driven design model.
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 need to separate ViewModels in my MVC project from my business models (Data access layer) which lives in a separate library.
Assume that I have Database Access Layer classes in a separate library. Our primary project (MVC) does know nothing about those classes and they talk to each other through an Interface. It’s easy enough to use IOC and resolve dependency injection using Ninject or something, right?
Now DataAccessLayer contains class named Car with properties Engine and Wheel. In my MVC project (which doesn’t know nothing about DataAccessLayer and its classes) I need to use some Car objects. So I have another Car class (it’s just a pure ViewModel) and it has the same properties – Engine and Wheel (of course in real app there will be some differences between model and viewmodel, for the sake of simplicity let’s ignore that)
IDataAccessLayer Interface has a method called IEnumerable GetAllCars() that returns list of DataAccessLayer.Car objects.
Now I need to create MVCProject.Car collection, iterate through IEnumerable which was returned by GetAllCars(), on every iteration I need to create a new MVCProject.Car object, populate Engine and Wheel properties, and finally add that object to the Collection.
So: everytime I have to create almost the same structures and somehow manage them in different places.
Here is the problem, see? Or it isn’t? I feel like it will end up into big mess if I don’t change that. Don’t repeat yourself principle violation as it is. Tell me please how to make it right. Using I don’t know proxies or prototypes or maybe some other design pattern which I suck anyway. Or some sort of a tool like Ninject (which I only know how to use as IOC container) or Automapper or whatever, which I probably will suck even more than I suck in design patterns.
I also don't see much of a reason to keep the DAL separate from the MVC layer. In case you're interested, here is the layout that I've used for multiple project and I find it is very usable and flexible.
DataObjects
Basic objects with only properties. Also includes enumerations which the DataObjects use.
DataAccess
Inherit from DataObjects and add GetByPrimaryKey, GetByForeignKey, GetByUniqueIndex, GetAll, etc., etc. Also contains the Caching layer where you would find StateCache, CountryCache, etc. for quick access to frequently used things. The "GetBy" methods will utilize the caching layer whenever possible.
Logic
Static classes, one for each DataObject\Access type. Includes logical work other than simple fetches as detailed in the DataAccess layer.
Web\Front-end
UI works with DataAccess and Logic layers to get and update objects as well as call other defined logical APIs.
I use my own custom-made code generator to generate 98% of this code (except the UI layer).
It sounds like your MVC library should know about your data-access library, shouldn't it?
Or, if you really want to keep your MVC and DAL libraries separate, you could always add a third library with references to both MVC and DAL. Then it could handle retrieving cars from the one library, and converting them to the other.
But again, I don't see why your controllers (or ViewModel, from what you've described) shouldn't have access to the DAL. Your car ViewModel would retrieve instances of Cars from the DAL, and go from there. So long as the way in which it receives the cars is coded through an interface, you should be able to stub that out later for your unit tests.
EDIT
So it looks like you think you'll be changing the entire DAL around later, and you want to minimize the difficulty of that? If that's the case, you might look at the adapter pattern. You would pass all your DAL objects to adapters, which would return to you objects in your business layer. Then, if your DAL changes, you just update your adapters.
I found a way to make it really ugly :)
The Goal: Caller doesn't know nothing about Model Entities at DataAccessLayer, and gets all the data through the interface.
How to get the data without manual mapping between Model and Viewmodel?
Through reflection.
public IEnumerable<T> GetCars<T>()
{
var lst = new List<T>();
_data.GetTable<Cars>().ToList().ForEach(x =>
{
var newCar = Activator.CreateInstance<T>();
typeof(T).GetProperty("Engine").SetValue(newCar, x.Engine, null);
typeof(T).GetProperty("Wheel").SetValue(newCar, x.Wheel, null);
lst.Add(newCar);
});
return lst;
}
It Works. But the biggest question here is it fair and considerable architectural decision? How the performance will be affected in a real life app?
I am writing ASP.NET website in which i break code into layer like form object class, Entity classes for business logic, Controller classes to control multiple entity class and finally data access classes.
All above mentioned class have their saperate dll(s) because Form object an business classes are shred among multiple component of project like website and Apllication (Exe)
I have following doubt
I would like to know whether i am doing right approach as per layered programming or not?
Where should we create object of class inside constructor of parent class or with in a function; Because in my case there are around 8-10 child class need to used inside parent class so where should i create clhild class object in constructor of parent class or inside function of parent class where i am using child object?
As mentioned above layered approach, in which layer i should create database connection?
Please help me?
I'm not sure if this helps (or answers your questions) but this is how we structure our applications with our development. The structure suits our needs really well and we (try to) employ a DDD approach.
DDD Solution Structure http://www.kanebarton.com/images/DomainDesign.png
I would like to know whether I am doing the right approach
If you mean from a "Layered" architecture perspective, then I would say yes. The idea is to create different layers of responsibility. In your case you are layering your application like:
UI Layer
Business Logic Layer
Controllers Layer - Possible improvement would be to move this into the Business Logic Layer and make it a separate namespace i.e. BusinessLogic.Controllers
DAL (Data Access Layer)
Which seems fair enough IMO.
You should really take a look at the The Repository Pattern. This basically creates a controller class which connects to your database (on create of the object) and then exposes methods (for that particular class) which will interact with your database. Your application also has an MVC feel to it, you should consider using the ASP.NET MVC Framework