I'm trying to wrap my head around repository pattern and dependency injection concepts for my ASP.NET MVC applications.
I ran across the article Repository Pattern with Entity Framework, and really liked how simple the code is. There doesn't appear to be that much code and it's all completely generic. That is, there's no need for multiple repositories for the different objects in the database as most people appear to be doing. This is just what I want.
However, the code is written for code first, which I'm not planning to use.
Questions:
Is there a good reason why the same code couldn't be used for applications that don't use code first?
Can someone recommend a better approach for my applications that don't use code first? (Keeping in mind that I'm absolutely sold on this generic pattern.)
Any other tips to help me move forward?
You can make a repository interface for any underlying data store. You can simply define an interface like so:
public interface IRepository
{
IQueryable<T> GetQueryable<T>();
void Insert<T>(T item);
}
Then, you can implement a class behind this which will implement it. It doesn't have to be code-first; you can back it with an ObjectContext created from an EDMX file, for example.
The key here is in creating the right abstraction. You can easily do that with an interface, and then implement it however you want behind the scenes.
Because you're using dependency injection, the implementation doesn't matter as much, as long as you've defined the contract correctly, the implementation (and testing of it) should be simple. And if it doesn't work, or you want a different data store altogether, you just tell your dependency injector to use a different implementation, the contract doesn't change.
The same can be said for any abstraction you create; you can have an interface that reads and writes data (like the article you reference does), you just have to pull the abstraction out.
Have a look on this. I think this link will help you most
http://www.codeproject.com/Tips/572761/Generic-repository-pattern-using-EF-with-Dependenc
In this link Generic repository pattern is used with dependency injection in MVC project without using code first approach.
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?
As far as I've been studying the Repository pattern, the "repositories" should be responsible for data persisting and basic querying tasks, and only for that. So in a typical repository I see something like this:
public interface IProductRepository {
Product GetByID(int id);
void Add(Product item);
void Update(Product item);
void Delete(Product item);
}
But I wonder what if one uses an ORM tool like DevExpress' XPO, a repository implementation would mostly consist of one-liner methods. Does it make sense to still create this abstraction level beside XPO?
One could point out the mocking and unit testing capabilities, but for example XPO provides a powerful in-memory persistence feature, which is perfect for unit testing in 99% of times.
I think I could mention EF or NHibernate as well, those have similar features.
An additional question: if - let's say - I don't implement the repository pattern in this manner, where shall I put more complex queriyng (for example based on complex criteria or user roles), or more complex item saving logic (with logging, validation, etc.)?
Thanks for any help.
UPDATE
What about defining a generic repository interface which type-independently addresses CRUD operetaions like this:
public interface IRepository : IDisposable {
T GetByID<T>(int id);
IQueryable<T> Query<T>();
T Create<T>();
void Update<T>(T item);
void Delete<T>(T item);
}
Then I can implement it easily with with XPO, EF, or whatever ORM I choose, even with JSON text files. Is it a good middle-way solution, or does it smell? The only drawback I can see is where would I put those more complex operations mentioned above, but probably I could inherit special interfaces from this when needed.
But I wonder what if one uses an ORM tool like DevExpress' XPO, a
repository implementation would mostly consist of one-liner methods.
Does it make sense to still create this abstraction level beside XPO?
It depends on coding a technology-specific ignorant domain when it comes to persist and read your domain objects.
You might think that XPO or any other OR/M does a lot of wrapping and abstraction, so it sounds stupid the repository pattern because is an unnecessary layer.
Well, I would say that one of most strong points when you decide to use the repository pattern is turning your domain agnostic about how it gets translated into what underlying store understands. An OR/M adds a lot of details and dependencies which may be hardly changed if you spread them across your domain code.
Have you ever realized that repository pattern might be the right tool to decide what persists your data based on a simple configuration switch (inversion of control)? I don't think about this for testing purposes: choose repository pattern because you want to define how your domain talks to data in a single point.
You can even make your code work with more than one version of the same OR/M technology, because newer versions might not fit an old requirement, but new domain operations are still able to instantiate a new repository version which takes advantage of newer version optimizations and capabilities!
TL;DR
Yes, even if your repositories have one-liner methods, they're still useful. Fight for the future!
Update
What about defining a generic repository interface which
type-independently addresses CRUD operetaions like this:
This is perfectly valid: it's called generic repository. In fact, in my own developments I'm always using this pattern.
I'm slightly new to Unity and IoC, but not to MVC. I've been reading and reading about using Unity with MVC and the only really useful thing I'm consistently seeing is the ability to get free DI with the controllers.
To go from this:
public HomeController() : this(new UserRepository())
{
}
public HomeController(IUserRepository userRepository)
{
this.UserRepository = userRepository;
}
To this:
public HomeController(IUserRepository userRepository)
{
this.UserRepository = userRepository;
}
Basically, allowing me to drop the no parameter constructor. This is great and all and I'm going to implement this for sure, but it doesn't seem like it's anything really that great for all the hype about IoC libraries. Going the way of using Unity as a service locator sounds compelling, but many would argue it's an anti pattern.
So my question is, with service locating out of the question and some DI opportunities with Views and Filters, is there anything else I gain from using Unity? I just want to make sure I'm not missing something wonderful like free DI support for all class constructors.
EDIT:
I understand the testability purpose behind using Unity DI with MVC controllers. But all I would have to do is add that one extra little constructor, nix Unity, and I could UnitTest just the same. Where is the great benefit in registering your repository types and having a custom controller factory when the alternative is simpler? The alternative being native DI. I guess I'm really wondering what is so great about Unity (or any IoC library) besides Service Locating which is bad. Is free Controller DI really the ONLY thing I get from Unity?
A good IoC container not only creates the concrete class for you, it examines the couplings between that type and other types. If there are additional dependencies, it resolves them and creates instances of all of the classes that are required.
You can do fancy things like conditional binding. Here's an example using Ninject (my preferred IoC):
ninjectKernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
ninjectKernel.Bind<IValueCalculator>().To<IterativeValueCalculator().WhenInjectedInto<LimitShoppingCart>();
What ninject is doing here is creating an instance of IterativeValueCalculator when injecting into LimitShoppingCart and an instance of LinqValueCalulator for any other injection.
Greatest benefit is separation of concern (decoupling) and testability.
Regarding why Service Locator is considered bad(by some guys) you can read this blog-post by Mark Seeman.
Answering on your question What is so good in Unity I can say that apart from all the testability, loosely-coupling and other blah-blah-blah-s everyone is talking about you can use such awesome feature like Unity's Interception which allows to do some AOP-like things. I've used it in some of last projects and liked it pretty much. Strongly recommended!
p.s. Seems like Castle Windsor DI container has similar feature as well(called Interceptors). Other containers - not sure.
Besides testing (which is a huge benefit and should not be under estimated), dependency injection allows:
Maintainability: The ability to alter the behavior of your code with a single change.
If you decide to change the class that retrieves your users across all your controllers/services etc. without dependency injection, you need to update each and every constructor plus any other random new instances that are being created, provided you remember where each one lives. DI allows you to change one definition that is then used across all implementations.
Scope: With a single line of code you can alter your implementation to create a singleton, a class that is only created on each new web request or on each new thread
Readability: The use of dependency injection means that all your concrete classes are defined in one place. As a developer coming onto a project, I can quickly and easily see exactly which concrete classes are mapped to which interfaces and know that there are no hidden implemetations. It means I can not only read the code better but empowers me to have the confidence to develop against the code
Design: I believe using dependency injection helps create well designed code. You automatically code to interfaces, your code becomes cleaner because you haven't got strange blocks of code to help you test
And let's no forget...
Testing: Testing is huge! Dependency injection allows you to test your code without having to write code specifically for tests. Ok, you can create a new constructor, but what is stop anyone else using that constructor for a purpose it has not been intended for. What if another developer comes along six months later and adds production logic to your 'test' constructor. Ok, so you can make it internal but this can still be used by production code. Why give them the option.
My experience with IoC frameworks has been largely around Ninject. As such, the above is based on what I know of Ninject, however the same principles should remain the same across other frameworks.
No the main point is that you then have a mapping somewhere that specifies the concrete type of IUserRepository. And the reason that you might like that is that you can then create a UnitTest that specifies a mocked version of IUserRepository and execute your tests without changing anything in your controller.
Testability mostly, but id suggest looking at Ninject, it plays well with MVC. To get the full benefits of IOC you should really be combining this with Moq or a similar mocking framework.
Besides the testability, I think you can also add the extensibility as one of the advantages. One of the best practices of Software Development is "working with abstractions, not with implementations" and, while you can do it in several ways, Unity provides a very extensible and easy way to achieve this. By using this, you will be creating abstractions that will define the contracts that your component must comply. Say that you want to change totally the Repository that your application currently uses. With DI you just "swap" the component without the need of changing a single line of code on your application. If you are using hard references, you might need to change and recompile your application because of a component that is external to it (In a different layer)
So, bottom line, IMHO, using DI helps you to have pluggable components in your application and have a SOLID application design
I am looking for a simple IRepository interface for my mvc web application,
I have done a lot of searching around, and there are as many opinions as there are people.
So i decided to ask the experts
If you can recommend a IRepository and IRepository interfaces that are commonly used and answer the basic CRUD and query operations ( to support filtering ).
If you know of frameworks that also include implementations and can work with EF 4 I would love if you can mention them.
Thank you.
Edit:
As #Ladislav suggests what is the alternative, always just call linq to ADO.net calls from my code? Is it a good idea to use a POCO repository that abstract creation of custom POCOS from my business model, I have a Jewel POCO class that need to be parsed from varies DB entries, is this a common practice with legacy systems where I can't touch the DB architecture but only the presentation
Stop. Patterns should be used when they are needed - when they solve some common problem - not because they exist. You obviously don't need it at the moment because you didn't write any single requirement what the repository should solve for you - such requirements are crucial if you want to choose a "good one" to start with. Anyway a good one usually evolve during your development, it is most often not defined upfront.
Also generic repository with EF is one of the most stupid patterns I have ever used in my own project. It is good only to be parent of specific repository. It works only in basic scenarios where you most often don't need repository at all.
Something to read: What is the point of generic repository
The repository pattern is pretty straight-forward...you really don't need to use an existing framework. You can build the interface(s) yourself. There are a number of good examples out there in blogs of people building their own and also allows them to have near 100% code coverage in their tests. Here's a few examples (but they all follow similar patterns):
Using Repository Pattern with Entity Framework (Gil Fink)
100% UNIT TESTABLE LINQ TO SQL REPOSITORY (Kazi Manzur Rashid) -- I'm actually following some of his examples in my work
Working together: LINQ to SQL, IRepository, Unit Of Work and Dependency Injection (Stuart Harris)
And there are a ton more.
I think building it yourself, especially if you're just learning the pattern, will definitely teach you a ton about the pattern and also give you insight into what works for your situation and what doesn't.
I hope this helps! Good luck.
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)