Repository pattern implementation with ninject - c#

In my project, I trying to implement repository pattern and unit of work.
I found some web site to describe how to implement it such as:
http://www.codeproject.com/Articles/688929/Repository-Pattern-and-Unit-of
http://www.codeproject.com/Articles/561584/Repository-Pattern-with-Entity-Framework-using
I was wondering, why is not generic Unit of Work and Repositories Framework? then try several search on internet and I found it,
http://genericunitofworkandrepositories.codeplex.com/
This framework is first code but my project is model first therefore is not work correctly?
Could you please suggest me model first framework like this?
My project is a internet web site with one database, If there is plausible reason I can change model first approach to code first approach.
Thanks for you time.

We've abstracted all the interfaces in our latest release into Repository.Pattern project https://genericunitofworkandrepositories.codeplex.com/SourceControl/latest#main/Source/Repository.Pattern, in plans to implement nHibernate provider. You are more than welcome to start implementing these interfaces, based on bandwidth at the moment, I cannot commit to any dates as of yet.

Related

C# Dependency Injection with Unity, a unit of work, a database and the ability to change database at runtime

So I am wrestling with this for quite some time now, but I can't seem to figure it out.
At first I had a datalayer in my solution. This layer is for the communication between the business and the database. It had a generic repository and context objects so it is easy to retrieve and send data from and to the database with EntityFrameWork 6. This all worked very good... but...
Now I notice that in my application (WebAPI 2) I need to change database at runtime. This is really hard to do. It should follow this path:
An external application does a call to my API. In the header of the request is set which database should be used (an Id, or a logic name or whatever, not important now). Before an action is executed some code should read this header-item and set the new connection to the repositories.
This is how I register the repositories for Unity:
container.RegisterType<IContexts.ILanguageCodes<LanguageCode>, Data.LanguageCodes>();
container.RegisterType<IContexts.ISecurityRoles<SecurityRole>, Data.SecurityRoles>();
To show you everything what the implementations of these interfaces are is very much.
To change the connection to an other database I have to change the DBContext, which I know where to find, but the code doesn't. So I started Googling.
Then I found this article: http://rob.conery.io/2014/03/04/repositories-and-unitofwork-are-not-a-good-idea/. I read it and all the stuff that is not good is in my project. I was like: Okay, lets start over on the datalayer.
THen I found this article: https://www.danylkoweb.com/Blog/a-better-entity-framework-unit-of-work-pattern-DD. I followed this and came pretty far. But got stuck on the part where the request comes in.
So basicly I am looking for this:
A way to change the connection to an other database at runtime with dependency injection, so I don't have to change the connection everywhere. In the end; the idea of DI is that you don't know where the implementation is, so in this case you don't know where all the connections are.
Does anybody have an example found on the internet I could use to try? Or maybe a good, small example I can focus on?
Long story, I hoped I could make it smaller. I hope someone can help me with this.
Thanks
When I need to support scenarios like this I have one "provisioning" or "configuration" database which holds the connectionstring for each customer/user/whatever. This is separate from the databases which map to the data my application needs.
Whenever the requests comes in you can configure your IOC container with the correct connectionstring, altough I don't know if unity supports this scenario, I know AutoFac / Ninject and most other containers allow changing the container.

scaffolding template for creating repositories

I'm a new comer to the Scaffold world to build repositories creating the CRUD operations.
There are a lot of scaffolding templates ,I'm so confused which one will suit my requirement .
I use asp.net web forms (not asp.net MVC)
I use Entity Framework 6 as ORM .
I want some help to clarify the main pillars we select one scaffolding template over one and what's the proper one for my case ?
NOTE : Right now i use T4Scaffolding .
I think you can use T4Scaffolding, as you already do. But why are you using a "scaffold"? I created my crud app with entity framework without scaffolding anything.
Anyway, the scaffolding tools are all very similar, so T4Scaffolding is perfect, IMHO.
I think you can find interesting this and this.
Let me know if you have other questions.
It looks like you are trying to generate repositories for each model class. If that's the case, my advice will be don't. Moreover, don't be tempted by Generic Repositories (anti-pattern) as well.
For Scaffolding
If you must use scaffolding for generating repositories around your model classes, you may refer to this link for scaffolding repositories using T4Scaffolding.
Note:
If you're using Visual Studio 2013/2015, you would have to use the T4Scaffolding.VS2015 nuget package instead of the older T4Scaffolding package (for older versions of VS).
Aggregate Roots
Firstly, repositories are created on aggregate roots and not per class.
Secondly, although debatable, but EF already implements these patterns.
You many want to read more on repositories; refer t the Matrin Fowler's excellent post.
Why Use Repositories anyway?
Also, there are a bunch of people against it as well importantly for good reasons.
See Rob Conery's post on it. Although, I would prefer using the below solution instead of the one recommended in the post.
The alternate?
BTW, you should consider using commands or tasks instead of respositories. Something like Ayende's post. Of course, you should evaluate your case and come up with your reasons to adopt it. It's just a suggestion, probably a good one ;)

MVVM approach, what's a good way? How to improve/speed up development?

this post is meant to have a list of suggestions on MVVM approach... What tools do you use, what do you do to speed up development, how do you maintain your application, any special ways of finding defects in this design pattern......
here is what I do:
So first i create my model/db with EF.
Then I create Views (either user controls or windows) with their respective viewmodel. I usually place the viewmodel in the same location as my view. But while starting the name of my view with "UC-name", I call my viewmodel just "name-model".
In my viewmodel I implement InotifyPropertyChanged
in my xaml view I have a resource of my viewmodel, and bind my grids/controls via the itemsource to the staticresource.
I try to do a lot of front end logic with triggers and styles and also place some code in the xaml.cs file if it regards logic for behaviour of my controls.
I can reach my viewmodel from my view (xaml + xaml.cs).
for communiation between viewmodels I use MVVM lights.
that's pretty much it.
Things I'm thinking about
I'm thinking of using T4 templates for generating viewmodel/view. What do you guys think of this. is this worth it?
when using MVVM light Messenger, we get a subscription based communication, and sometimes I find it hard to track what has changed in my DataContext. Any suggestions on this?
any other improvements or suggestions are more than welcome !
Answering first question regarding View/ViewModel generation I think for CRUD cases it makes sense to use some tools, otherwise it won't be that beneficial.
Pretty nice basic scaffolding implementation example you can find here: WPF CRUD Generator. Also WPF solution by DevExpress looks really promising.
There are at least couple Codeplex projects addressing View/ViewModel generation:
WPF Scaffolder
ViewModel Tool by Clarius
But I am quite pessimistic about T4 for such scenarios. I think writing and polishing own T4's will take you much more time than adoption of existing tools.
Regarding MVVMLight messenger I can say that it will take you some time to get used to it. And as soon as you will understand difference between "regular" and message driven MVVM you'll be able to use it in most efficient way. Very nice article about messenger is Messenger and View Services in MVVM. And want to add a really important quote from there:
A Word of Caution About Messenger
Messenger is a powerful component that can greatly facilitate the task
of communication, but it also makes the code more difficult to debug
because it is not always clear at first sight which objects are
receiving a message. Use with care!
I'm very much a proponent of Domain-Driven Development (DDD). First I have the designer write specifications, roughly adhering to the methodologies in Behavior-Driven Development (BDD). This then forms the basis of unit tests for Test-Driven Development (TDD), for which I use NUnit. For the domain layer itself I start with an Anemic Domain Model i.e. entity classes containing mostly properties and virtually no methods; there are plenty of arguments both for and against this but personally I find it works well. Coupled with this is the Business Logic Layer (BLL) which knows only about the domain entities.
For the Data Access Layer (DAL) I prefer NHibernate, it supports all the usual things you would expect like lazy loading and repository management etc but particularly important is the Object Relational Mapping (ORM) i.e. the bit that translates between your domain entities and the underlying database representation.
One of the problems with NHibernate, in my opinion, is that it uses XML files to do the mapping for the ORM. This means two things: first is that any errors you introduce won't get picked up until run-time. Secondly it's not really a proper "solution" to ORM at all, instead of writing mapping classes you just wind up writing XML files. Both of these problems can be solved by using Fluent. Fluent solves the first problem by replacing XML files with C# files, so your mapping declarations are now done in code which will usually pick up errors at compile-time. It solves the second problem by providing an auto-mapper, which looks at your entities and generates the necessary mapping files automatically. This can be manually overridden if and where needed, although in practice I find I seldom need to. Since the auto-mapper uses reflection is does tend to be a bit slow but it can be run in an offline utility and then saved to a configuration file that is loaded at run-time for near-instant start-up; the same utility can also be used to create your database automatically. I've used this tech with MySql, MS Server and MS Server CE...they've all worked fine.
On the other side of the tier is your view model. I've seen a lot of projects create an almost 1:1 mapping of domain entities to view model classes, I may infuriate MVVM purists by saying this but I really don't see the point in doing all that extra work for something that isn't really needed. NHibernate allows you to provide proxies for the classes it creates, using Castle Dynamic Proxy you can set an intercepter to your NHibernate session factory that automatically injects INotifyPropertyChanged notification to all of your entity properties so that they work with the WPF binding mechanism. Another product, uNhAddIns, allows you to replace any lists with an ObservableCollection in order to get INotifyCollectionChanged support (for reasons I won't go into you can't just put an ObservableCollection into your entities without it seriously affecting performance).
If you're designing and building your application properly using technologies like these and fully unit-testing along the way then you're going to need some way of handling Inversion of Control (IoC) so that you aren't passing object references around all over the place, and for that you'll need a dependency injection framework. My personal preference is Ninject but Unity is pretty good too. Dependency injection is particularly important for good database session management (so that all relevant objects reference the same session), a good rule is one session per WPF form or one per web request.
There are lots of other little things I use to make life easier (MVVM Lite, log4net, Moq for mocking objects for unit testing etc) but this is my core architecture. It takes a while to set up but once you've got it all going you can build fully functional database applications in literally minutes without any of the headaches traditionally associated with layer management in tiered enterprise applications...you just create your domain entities and then start coding for them. Your schema is created automatically, your database is created automatically, you can use your entity classes to fill your database for immediate stress testing and you have full WPF support without having to pollute your entity classes with code or attributes not actually related to the domain. And since all development is driven by anemic domain entities your data is already in the perfect format for serialization into html/ajax/soap etc when you want to give your app web capablities.
You'll notice that I haven't discussed the presentation/XAML layer, mainly because that part is now straightforward. Using a decent architecture you can actually create a fully working and tested application that then only needs pure XAML added to turn it into a releasable product.

Repository Pattern in Mvc 4.0

I am having a project which is in Mvc 4.0. The project has already included EF in it nad using its classes with database first Approach. I have to do some work in it using repository pattern. I have read many blogs and I am still confused with how to actually integrate the Entity Framework with Repository. From where I have to start. I am reading this example
The explanation is okay but how can I merge the both concepts.What I tried is created a model class as the above link has suggested but in the above link in student class they have taken list of Icollection where enrollment is table in database . I am also passing my table name to list but not working.
Total Process I have done. Please tell me if this right or Wrong
Step1: I created a database named School
Step2 : I added entity framework in the Project.
Step3: I am now creating a model of the same properties as the Student table has.
Step4 : where I am now stucked. How will I create a Icollection??
Please help as soon as it can be possible. I will be thank ful to you.
Check out this question Unit Of Work & Generic Repository with Entity Framework 5 I think it is described well there.
Here is complete package you can use http://www.nuget.org/packages/Repository.EntityFramework/
And one more link: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application.
BUT before implementing repository pattern I would suggest you to think "Do you really need it?".
If you would like to see a real world scenario of how the Repository is implemented then I suggest you check out some open source projects.
Nop Commerce
Uses the repository pattern and dependency injection
http://nopcommerce.codeplex.com/
Videos
There is also the ASP.NET video series (free) about building an MVC Storefront
http://www.asp.net/mvc/videos/mvc-1/aspnet-mvc-storefront/aspnet-mvc-storefront-part-2-the-repository-pattern
Open Access samples
Telerik has some great examples using their ORM (OpenAccess). Even though it uses a different ORM, the repository pattern is still applicable to EntityFramework.
http://www.telerik.com/products/orm.aspx
Here is an example that you might find useful: Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application, from www.asp.net
Here is some article which explain basic about Repository Pattern also sample example with source code.
CRUD Operations Using the Repository Pattern in MVC
Repository pattern, done right
Generic Repository Pattern in MVC3 Application with Entity Framework
public class AccountBrandRepository : GenericRepository<AccountBrand>
{
TestEntities _context;
public TestRepository(IUnitOfWork unitOfWork)
: base(unitOfWork as VoltEntities)
{
if (unitOfWork == null)
throw new ArgumentNullException("unitOfWork");
_context = unitOfWork as TestEntities;
}
}

"Modules" in Repository Pattern

We're using a Repository Pattern in our latest project. But we have find some difficulties implementing a "module" to that architeture.
In the below image, you can see how the main solution is tiered and how the "module" is tiered.
What we wanted to do is having the module without the responsability of the data access/handling.
That's why we dont have the Repository Pattern there.
Oh, and we are using NHibernate so we are expecting that saving our module in the main bussiness tier will respect the chain of relationship defined in the Modelo Tier in the "module".
Have a look at the following page http://blog.bobcravens.com/2010/06/the-repository-pattern-with-linq-to-fluent-nhibernate-and-mysql/
The author gives a brief explanation about the repository pattern and how he used it on Nhibernate with linq, but you could also use HQL ...
If you search for "repository pattern nhibernate" you'll find a wealth of articles demonstrating the technique.
However, I think it's important to ask as to whether you need to abstract NHibernate any further. In essence, NHibernate can be your repository.
http://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer

Categories