Design patterns advice - separating ViewModels from domain models - c#

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?

Related

Object added to view model inherits from seperate model project, does it break MVVM to add reference?

I have (many more than, but restricting focus to) two class libraries for the model, and another library for view models.
One of the libraries is named Condenser, and has a class called WaterCooledCondenser, which inherits from the HeatExchanger class in the Subcomponents project. The condenser is business logic, but it was designed for the view model to interact with (it is part of the Model). When I create a new Condenser in the view model it says that HeatExchanger is not referenced, and to add a reference to Subcomponents... I don't think the view model has any business knowing anything about the classes in that library, they are only meant to provide structure to the Model.
Would adding a reference to the class library violate MVVM? Is there another way around having the view model know anything about the structure of the model?
If these are third party libraries, you may be out of luck. But in general, I would say that your ViewModel should only know how to interact with Interfaces of another library. This way if the library changes implementation it should not beak if the interfaces are the same.
This being said, knowing the basic structure of the model is allowed in MVVM. However keeping the Business Logic and Models completely separate becomes harder when you know the specifics of your class. In order to prevent this interfaces are great tools in future proofing your code.
I would take what I say with a grain of salt; this is completely based on my experience in working within this design pattern.

web forms, autofac, EF newing up models?

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.

Is there a benefit in using the repository pattern to simplify the controller?

I have created quite a few projects where my business logic has been directly accessing my data layer. Since its the only way I have been setting up my MVC projects, I cannot say for sure where the system has been lacking.
I would, however, like to improve on this. To remove many return functions from my controllers, there are 2 ways I see to achieve the same goal.
Including these return functions as methods of the model classes(doesnt make sense, since the datacontext would need to be initialized within every model).
Using a repository
After reading up a bit on repositories, I haven't come across any instances where "Thinning your controllers" may be a 'pro' to using a repository(a generic repository, could be related to this).
For an understanding of the answer I am looking for, I would like to know if, besides the above mentioned reason, I should use a repository. Is there really a need for a repository?In this case, my project will only be reading data (Full CRUD functionality wont be needed).
There is definitely a need for a repository. Every class should only have one real responsibility where possible; your controller's job is simply to 'give' information to the view. An additional benefit to this is if that if you do create a repository layer then, providing you make interfaces for them, you can make your solution a lot more testable. If your controller knows how to get data from a database (past using a repository - or similar) then your controller is "doing" more than one thing, which violates the single responsibility principle.
I used to use a generic repository pattern using the library SharpRepository, however I found that I needed more fine-grained control over what each of my repositories had access to (for example, there were some repositories I did not want to have mutation control and only be read-only). As a result I switched back to using non-generic repositories. Any half-decent IOC tool will be able to register your repositories based on convention (i.e, IFooRepository maps to FooRepository), so the number of classes is not really a factor.
As a commentor mentioned your title doesn't really sum up your question, so I'll summarize it for other answer authors:
Is there a benefit in using the repository pattern to simplify the controller?

Refactoring Large Codebehinds - Repository pattern and Extension methods

I was hoping someone could help clarify my options regarding refactoring methods from code-behinds from ASP.NET webforms pages.
As background, we have spent some time recently implementing the repository pattern in both a generic and non generic sense, which has enabled us to move a lot of the DAL methods out of the codebehinds, which is great.
What I'm struggling to finalise, is a sensible approach to moving application logic methods out of the codebehinds which specific focus on the repository/DAL and how best to structure the BL classes.
Here are the two options I am considering at present:
1.Create a Business Logic class per codebehind and from this, expose
methods like getProject(int id) which would behind the scenes,
access a repository instance of repo.GetById(int id)
The benefit of this as far as I can see would be the following:
seperate app logic from the codebehinds, allowing them to be simple
allowing testable methods at the BLL (with some tweaking), kind of synonymous with controller classes in MVC (this is still webforms though)
Doesn't expose the repository directly
The downside would be:
A lot of wrapper methods in the BLL which don't really do anything
besides hide the repository methods
2.Write extension methods on my entity types, e.g. Project.getUsers() which would access a repository instance method allowing BL to be stored without the need for a specific BLL class, thereby reducing the duplication of the wrapper methods in each BL class.
The benefit of this would be:
No need to have a BL as such, storing methods with their entity type
Less wrapper methods, as there wouldn't be a need for ProjectBL.getUsers(projectid) and UserBL.getUsers(projectid) which both call repo.getProjectUsers(projectid) behind the scenes, simple Project.getUsers() from both codebehinds
The downside of this as far as I can tell:
If I introduce new types in the future, e.g. 'SubProject' getUsers() needs to be re-implimented
I'm not too keen on extension methods in general and not sure if this is the right place to use them!
I'm a little unsure which is 'better' practice, or if I've missed a better option all together. It may be worth knowing that initially the repository was being instantiated in the codebehind and accessed directly, but as I understand things, this is not ideal as we risk returning things like IQueryable from the repository and making DAL methods which can be manipulated in codebehind to produce inconsistent results.
The model I have found to be most effective with ASP.NET Webforms is the bind/unbind pattern. In this pattern, the only things you implement in the codebehind itself are event handlers (which will call back to more abstracted, logic-heavy methods in a BLL of some sort) and one method each to transfer data from (Bind) and to (Unbind) an instance of a domain object or DTO.
By structuring the codebehind in this way, the codebehind class becomes concerned only with the interop between logic and presentation, and so becomes quite thin in most cases. The data it will deal with will be primarily primitives and the DTO, and it will not require any knowledge of the DAL (at least, individual page codebehinds won't; you may set up your master page or a base class for your codebehinds to have DAL-touching methods common to wide swaths of your site, basically making this base class your Controller layer in code).
One other thing to keep in mind is that, depending on structure, it can be very simple to unit-test your codebehind classes. You can even TDD them, to a point; the declaration of basic GUI elements in the markup (and their object representations in the codebehind) is still best left to the IDE, but a public codebehind class with publicly-accessible members can be easily instantiated in a unit test, and the public methods exercised.
#KeithS I'm going to mark this one as accepted as no one else seems to have any suggestions! In case you curious I've opted to go more for the second approach, basically in my application I have some logical 'sections' such as 'Projects' or 'ApprovalForms' and I've gone with creating a single BL class per section rather than one per codebehind.
This does mean the class can contain methods which can be a bit varied (not a single purpose), but it does prevent me having tons of classes with basically the same method accessed from a different context. It is forcing me to write wrapper methods around the repository methods which feels a bit W.E.T. but it does mean that I can provide a common method for returning data to the front end, reducing the chance of having differing implementations.

DAL design question

I need to design a Data access layer DAL .Net Enterprise library version 3.5 Data access application block (DAAB)
In my application,I've various logical modules like Registration, billing, order management, user management,etc
Am using C# business entities to map the module objects to database tables and then return the List collection to the client.
I would like to design my DAL in such a way that if tomorrow we decide to use some other data access framework we should have minimal code change.
Given this, how do i design my class structure?
I thought I would have a class DbManagerBase which would be a wrapper over existing .net DAAB
This class DbManagerBase would implement an interface called IDbManagerBase which would have public methods like ExecuteReader, ExecuteNonQuery, etc.
The client class ie. RegistrationDAL,UserManagermentDAL would have the following code inside each of its methods:
IDbManagerBase obj= new DbManagerBase()
obj.ExecuteReader(myStoredProcName)
.
.
.
is this a good OOPS design?may i know any better approach please?or do i need to use inheritance here?
Can i have all the methods in DbManagerBase class and RegistrationDAL,UserManagermentDAL classes as static?I guess,if i've methods as static then the above interface code wont make any sense...right???
To truly abstract the DAL I'd use the repository pattern.
To answer a few of the questions:
Can i have all the methods in
DbManagerBase class and
RegistrationDAL,UserManagermentDAL
classes as static?
I would probably go with a non-static approach cause it gives the flexibility to better control instantiation of the DALs (eg. you could create instances of them from a factory), also it will allow you to have two DALs in place that are talking to different DBs in a cleaner way. Also you will not need to create an instance of the DbManagerBase in every object since it would be an instance member.
Regarding IDbManagerBase having ExecuteReader, ExecuteNonQuery and obj.ExecuteReader(myStoredProcName)
I would be careful about baking the knowledge about database specific concepts in too many places. Keep in mind some DBs to not support stored procedures.
Another point is that before I went about implementing a DAL of sorts I would be sure to read through some code in other open source DALs like NHibernate or Subsonic. It is completely possible they would solve your business problem and reduce your dev time significantly.
If you are looking for a small example of a layered DAL architecture there is my little project on github (it is very basic but shows how you can build interfaces to support a lot of esoteric databases)

Categories

Resources