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.
Related
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?
I have a Business Layer, whose only one class should be visible to outer world. So, I have marked all classes as internal except that class. Since that class requires some internal class to instantiate, I need other classes to be marked as public and other classes depend on some other classes and so on. So ultimately almost all of my internal classes are made public.
How do You handle such scenarios?
Also today there is just one class exposed to outer world but in future there may be two or three, so it means I need three facades?
Thanks
Correct, all of your injected dependencies must be visible to your Composition Root. It sounds like you're asking this question: Ioc/DI - Why do I have to reference all layers/assemblies in entry application?
To quote part of that answer from Mark Seeman:
you don't have to add hard references to all required libraries. Instead, you can use late binding either in the form of convention-based assembly-scanning (preferred) or XML configuration.
Also this, from Steven:
If you are very strict about protecting your architectural boundaries using assemblies, you can simply move your Composition Root to a separate assembly.
However, you should ask yourself why doing so would be worth the effort. If it is merely to enforce architectural boundaries, there is no substitute for discipline. My experience is that that discipline is also more easily maintained when following the SOLID principles, for which dependency injection is the "glue".
After doing a lot of research I am writing my findings, so that it may be of some help to newcomers on Dependency Injection
Misunderstandings regarding my current design and Dependency Injection:
Initial approach and problem(s) associated with it:
My business layer was having a composition root inside it, where as
it should be outside the business layer and near to the application
entry point. In composition root I was essentially having a big factory referred as Poor Man's DI by Mark Seemann. In my application starting point, I was creating an instance of this factory class and then creating my only (intended to be) visible class to outside world. This decision clearly violates Liskov's Principle which says that every dependency should be replaceable. I was having a modular design, but my previous approach was tightly coupled, I wasn't able to reap more benefits out of it, despite only some code cleanliness and code maintainability.
A better approach is:
A very helplful link given by Facio Ratio
The Composition root should have been near the application root, all dependency classes should be made public which I referred initially as a problem; making them public I am introducing low coupling and following Liskov's substitution which is good.
You can change the public class to the interface and all other parts of the program will only know about the interface. Here's some sample code to illustrate this:
public interface IFacade
{
void DoSomething();
}
internal class FacadeImpl : IFacade
{
public FacadeImpl(Alfa alfa, Bravo bravo)
{
}
public void DoSomething()
{
}
}
internal class Alfa
{
}
internal class Bravo
{
}
I can see three solutions, none real good. You might want to combine them in someway. But...
First, put some simple parameters (numeric, perhaps) in the constructor that let the caller say what he wants to do, and that the new public class instance can use to grab internal class objects (to self-inject). (You could use special public classes/interfaces used solely to convey information here too.) This makes for an awkward and limited interface, but is great for encapsulation. If the caller prefers adding a few quick parameters to constructing complex injectable objects anyway this might work out well. (It's always a drag when a method wants five objects of classes you never heard of before when the only option you need, or even want, is "read-only" vs "editable".)
Second, you could make your internal classes public. Now the caller has immense power and can do anything. This is good if the calling code is really the heart of the system, but bad if you don't quite trust that code or if the caller really doesn't want to be bothered with all the picky details.
Third, you might find you can pull some classes from the calling code into your assembly. If you're really lucky, the class making the call might work better on the inside (hopefully without reintroducing this problem one level up).
Response to comments:
As I understand it, you have a service calling a method in a public class in your business layer. To make the call, it needs objects of other classes in the business layer. These other classes are and should be internal. For example, you want to call a method called GetAverage and pass it an instance of the (internal) class RoundingPolicy so it knows how to round. My first answer is that you should take an integer value instead of a class: a constant value such as ROUND_UP, ROUND_DOWN, NEAREST_INTEGER, etc. GetAverage would then use this number to generate the proper RoundingPolicy instance inside the business layer, keeping RoundingPolicy internal.
My first answer is the one I'm suggesting. However, it gives the service a rather primitive interface, so my second two answers suggest alternatives.
The second answer is actually what you are trying to avoid. My thinking was that if all those internal classes were needed by the service, maybe there was no way around the problem. In my example above, if the service is using 30 lines of code to construct just the right RoundingPolicy instance before passing it, you're not going to fix the problem with just a few integer parameters. You'd need to give the overall design a lot of thought.
The third answer is a forlorn hope, but you might find that the calling code is doing work that could just as easily be done inside the business layer. This is actually similar to my first answer. Here, however, the interface might be more elegant. My first answer limits what the service can do. This answer suggests the service doesn't want to do much anyway; it's always using one identical RoundingPolicy instance, so you don't even need to pass a parameter.
I may not fully understand your question, but I hope there's an idea here somewhere that you can use.
Still more: Forth Answer:
I considered this a sort of part of my first answer, but I've thought it through and think I should state it explicitly.
I don't think the class you're making the call to needs an interface, but you could make interfaces for all the classes you don't want to expose to the service. IRoundingPolicy, for instance. You will need some way to get real instances of these interfaces, because new IRoundingPolicy() isn't going to work. Now the service is exposed to all the complexities of the classes you were trying to hide (down side) but they can't see inside the classes (up side). You can control exactly what the service gets to work with--the original classes are still encapsulated. This perhaps makes a workable version of my second answer. This might be useful in one or two places where the service needs more elaborate options than my first answer allows.
Forgive the title, it's simpler than it sounds.
I've got a class, StickerBook. It contains some stickers, List<Sticker>.
When it's time to see if there any stickers waiting to be added, should StickerBook.CheckForNewStickers() handle the logic of looking for them and then adding them, or should a new class, NewStickerChecker check for and then add them to the StickerBook?
A pretty basic concept I know, I just can't wrap my head around it.
Pretty sure there's no right or wrong answer to this. Either way you seem to be encapsulating the logic rather than making the internals of the class (List) open to all which is generally a good thing.
Putting logic into a separate service class (and having this class implement an interface) could make unit testing easier if you then pass this interface to other pieces of code as a dependency. I think it's conceptually easier to mock up a service class and pass around the actual simple entities during testing rather than mock up entities with complex logic on them.
Well, it depends on what's your general approach to structuring the code and modelling of objects. That said, the Single Responsibility Principle states that object should have only one reason of existence, so I would favor the NewStickerChecker as a class.
there is no black and white and this could be subjective, in my experience if there is an entity which contains a collection of sub-entities, like in your case the book contains a list of stickers, you could load them inside the entity.
After all OOP defines that classes contain data and logic required to manipulate that data ;-)
P.S. just as disclaimer, you are talking of entities in the spirit of Business Entities and not in the Entity Framework light (... not that it would change too much anyway but just for the question's tagging ).
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 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)