I am beginning to wonder if ANYONE uses NHibernate with a WPF or Win Forms application, such is the dearth of examples or text books on the subject. I am struggling to find "best practices" for its use, and especially session and sessionfactory management, with an MVVM WPF application and repositories.
To jump right in, it seems that the preference is to supply the repository with an ISession. But, where is this instantiated - in the ViewModel? - and if so, does this not created an uncomfortable dependency between the VM and NH (or is that just simply unavoidable, no matter how you dress it up?) Any implications for a multi-user application?
With the repository pattern - should I use one large repos. for all objects (and hence one session) or, as seems more manageable at first sight, should the repositories be split up in some logical business-related way? - but, if split up, how then to manage sessions? In my case, a form/window does not just deal with one entity (maybe it should...?) but with more than one. I don't want the ORM side to be dictated by the UI form design (maybe it should!?)
And then again, SessionFactory - where, and when to create it - once, at app startup?
Any good pointers or references for an NH app that is not web-based would be much appreciated.
Here is a reference to a similar question, but it was posed over four years ago: Using Unit of Work design pattern / NHibernate Sessions in an MVVM WPF
Many thanks
I've been using NHibernate with MVVM for years, once you get it going it's great. The MSDN article Building a Desktop To-Do Application with NHibernate covers the whole issue of session management rather well and is definitely worth a read.
One thing that will make life a lot easier is the use of a good dependency injection framework. I personally use Ninject and one of the things I particularly like is its support for object scoping. For example you can set your NHibernate session object (and thus the entity repositories) to scope to the pages in your application using InScope, so anything within the hierarchy of a given page that asks the injection framework for a session object will all get a pointer to the same instance.
Lots of other advantages to going down this route, for example it's very easy to use things like Castle Dynamic Proxy to inject property change notification to classes so that the entities you get back from your database queries support it automatically and thus can be bound to directly in the view or subscribed to by other class instances in your model or view model. Same goes for lists, which can be problematic because replacing a database entity list with an ObservableCollection<> can cause the database to think the entire list has changed which in turn causes performance problems when every single entity starts serializing itself back to disk regardless of whether or not it has actually changed.
Related
I am fairly new to Spring. Can anyone tell me which layer of MVC does spring configuration file reside. As per definition of M, V and C, I think it should be controller layer but I don't know if it is right.
I'm not sure this is really an answer but it is too long for a comment.
I think it would be unhelpful to think of MVC as too rigid. Historically it came forth (MUCH earlier than most people know) as a separation of concerns. This paradigm predates the web by at least 10 years.
When end user devices started having enough brains to do useful work it became obvious that just because your PC (not quite so dumb terminal) could store program code it was not the right place from which to make database calls and ship results sets. One of the first client-server applications I ever saw had as just one of its growing pains the brilliant idea to download all the possible customers into a pick list on a diskless unix workstation. Unfortunately that customer list was over 100,000 entries. Needless to say that didn't work well.
The very first separation of concerns I know of was an IBM philosophy dating to the mid-1980. Each piece of the application in a 2 or 3 tier model was split into distinct services that could be compartmentalized. They were:
Presentation Service (aka View)
Application Service (general utility functions)
Application Logic (aka Domain; aka Controller)
Data Manipulator / Data State Controller (aka Model)
It is really amazing that there are so few new ideas under the sun. The names change. The concepts don't. The main thing missing from the above list is the SERVICE interface (aka Spring #Service). They had not delineated clear entry points to the Application Logic yet. Also Application Service lost its focus in being called out and just slunk back into the UTIL folder where it probably belongs.
As to your question, by default #Configuration stuff is Controller of MVC. Not because the other legs can stand on their own, they can't. But because it obviously isn't a Model or a View.
You would probably benefit from reading about Spring PRE Spring Boot. Personally I really dislike Spring Boot. It is a bridge too far IMO in giving up control of the environment.
There are really fascinating (well to me at least) things to know about multiple contexts and parent child relationships. This is more than just a completely academic exercise if you properly structure your Model and Controller stuff separately from your View stuff.
I am also fond of using Spring Profiles to swap out Oracle and H2 so tests can complete within the normal human lifespan. Not to mention being repeatable, which direct database access almost certainly is not.
Has anyone created an empty solution stack for .NET (C#) that incorporates an IoC framework for DI using multiple projects?
I've struggled for months to create a good reusable stack that has:
MVC UI web app
Empty BLL project (will add real entities later)
Empty DAL project (will add real daab classes later)
Reference/Search data tier
Includes an IoC framework
Sample usage of DI in a Home controller that can reach all the way to the DAL thru the entity layer or to ref/search tier all thru interfaces
Must NOT set a hard reference of any concrete classes at the UI layer
I've attempted this a few times but I always get hung up at #6 and I'm missing something basic in the structure of the stack. Has anyone managed to do this and have a sample solution to show how it's structured? I can create stacks all day long and add a IoC framework, but completely fail at getting it structured so that no concrete references are added to the UI layer. How else can the interface/concrete resolution of objects take place?
Surely some of you scholars have nipped this in the bud, please share some of this enlightenment with me :-)
ps - I've read Mark Seeman's book more than once.. I understand the concept of Composition Root... but have never seen one in use in an NTier solution and have been unable to implement the theory successfully
What I am looking for is a fleshed out solution stack of multiple projects that can be used as a base to start from. One that implements the composition root successfully and can be used to teach the SOLID principles by doing instead of telling. A solution that brings it all to life. See this question for reference.
My Shuttle Wiki FOSS has some elements of what you are after:
http://shuttlewiki.codeplex.com/
Although not every concern is in its own proejct/assembly I have found that it is not worth the effort to tease them apart unless you are really going to use the relevant assembly somewhere else. That being said, it is still very easy to split them out as care has been taken to keep the concerns decoupled.
Scanned through some of the comments. My opinion is that no project structure or technique should be used to try and prevent or protect other developers from using certain classes. Junior developers have to learn the ropes at some stage and some quick code walkthroughs would pick up coding not consistent with what you are trying to achieve.
Take a look at mine:
using repository pattern, ninject, entity framework 6, ...
https://github.com/mesuttalebi/NTierCSharpExample
I've built a site in MVC3 using EF 4.0 using the Repository pattern. Everything was going good but I'm starting to run into a lot of "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects" errors. It seems that my repository layer is getting the contexts all mixed up, so I figured it might just be easier to start a new EF4.1 project.
At first I looked into Repository Pattern + Unit of Work, but came across some threads saying that this isn't needed for EF4.1. I came across this thread saying "DbContext is implementation of unit of work pattern and IDbSet is implementation of repository pattern.". I figured maybe then I could just use that. Upon further inspection though it seems that DbContext uses the Code First approach, which as far as I can tell will drop and create the database again if the POCOs change. I need to keep the data in my database, so as far as I can tell that option is out.
My head is spinning right now with EF options. Is the Repository pattern needed with EF4.1? Is DbContext meant for working on databases that are already full of data? Is there a better way of managing the entity contexts that don't involve these?
Any push in the right direction would be great =/
A few comments. For details I recommend to do some basic research using a search engine.
...I'm starting to run into a lot of "The relationship between the two
objects cannot be defined because they are attached to different
ObjectContext objects" errors. It seems that my repository layer is
getting the contexts all mixed up, so I figured it might just be
easier to start a new EF4.1 project.
If you have this error you did something wrong. EF 4.1 won't protect you to do the same mistake again because you also cannot change relationships between objects that are attached to different DbContexts. You just have to analyze and debug your code and find the source of the problem.
...this thread saying "DbContext is implementation of unit of work
pattern and IDbSet is implementation of repository pattern.". I
figured maybe then I could just use that...
ObjectContext and ObjectSet<T> is an implementation of those patterns as well. This is no reason to change the version of Entity Framework.
Upon further inspection though it seems that DbContext uses the Code
First approach...
You can also use Database First and Model First approach with DbContext.
...which as far as I can tell will drop and create the database again
if the POCOs change. I need to keep the data in my database, so as far
as I can tell that option is out.
You can turn that feature off. Also, EF 4.3 has a migration feature which helps to update and evolve an existing database schema.
Is the Repository pattern needed with EF4.1?
No. It's also not needed for ObjectContext. To be precise, it's not needed that you write your own (abstract) repository of top of EF, because EF is already an implementation of that pattern.
Is DbContext meant for working on databases that are already full of
data?
Yes. The additional feature to create a database from code (Code-First) is mainly a productivity tool for the development phase of your application which is supposed to be disabled in production.
I’m developing a part of an application, named A. The application I want to plug my DLL into, called application B is in vb 6, and my code is in vb.net. (Application B will in time be converted to vb.net) My main question i, how is the best way for me to organize my code (application A)?
I want to split application A into layers (Service, Business, Data access), so it will be easy to integrate application A into B when B is converted to vb.net. I also want to learn about all the topics like layered architecture, patterns, inversion of dependency, entity framework and so on. Although my application (A) is small I want to organize my code in the best way.
The application I’m working with (A) is using web services for authenticating users and for sending schema to an organization. The user of application B is selecting a menu point in application B and then some functions in my application A is called.
In application A I have an auto generated schema class from an xsd schema. I fill this schema object with data and serialize the object to a memory string (is it a good solution to use memory string, I don’t have to save the data yet), wrap the xml inside a CDATA block and return the CDATA block as a string and assign the CDATA block to a string property of a web service.
I am also using Entity framework for database communication (to learn how this is done for the future work with application B). I have two entities in my .edmx, User and Payer.
I also want to use the repository pattern (is this a good choice?) to make a façade between the DAL and the BLL.
My application has functions for GeneratingSchema (filling the schema object with data), GetSchemaContent, GetSchemaInformation, GenerateCDATABlock, WriteToTextFile, MemoryStreamToString, EncryptData and some functions that uses web services, like SendShema, AuthenticateUser, GetAvalibelServises and so on.
I’m not sure where I should put it all?
I think I have to have some Interfaces like IRepository, ISchema (contract for the auto generated schema class, how can I do this?) ICryptoManager, IFileManager and so on, and classes that implements the interfaces.
My DAL will be the Entity framework. And I want a repository façade in my BLL (IRepository, UserRepository, PayerRepository) and classes for management (like the classes I have mention above) holding functions like WriteToFile, EncryptData …..
Is this a good solution (do I need a service layer, all my GUI is in application B) and how can I organize my layers, interfaces, classes an functions in Visual Studio?
Thanks in advance.
This is one heck of a question, thought I might try to chip away at a few parts for you so there's less for the next guy to answer...
For application B (VB6) to call application/assemblies A, I'm going to assume you're exposing the relevant parts of App A as COM Components, using ComVisibleAttributes and similar, much like described in this artcle. I only know of one other way (WCF over COM) but I've never tried it myself.
Splitting your solution(s) into various tiers and layers is a very subjective/debatable topic, and will always come down to a combination of personal preference, business requirements, time available, etc. However, regardless of the depth of your tiers and layers, it is good to understand the how and the why.
To get you started, here's a couple articles:
Wikipedia's general overview on "Multitier Architectures"
MSDN's very own "Building an N-Tier Application in .Net"
Inversion of Control is also a very good pattern to get into right now, with ever increasing (and brilliant!) resources becoming available to the .Net platform, it's definitely worth infesting some time to learn.
Although I haven't explored the full extent of IoC, I do love dependency injection(a type of IoC if I understand correctly though people seem to muddle the IoC/DI terms quite a lot). My personal preference for DI right now is the open source Ninject project, which has plenty of resources online and a reasonable wiki section talking you through the various aspects.
There are many more takes on DI and IoC, so I don't want to even attempt to provide you a comprehensive list for fear of being flamed for missing out somebody's favourite. Just have a search, see which you like the look of and have a play with it. Make sure to try a couple if you have the time.
Again, the Repository Pattern - often complemented well by the Unit of Work Pattern are also great topics to mull over for hours. I've seen a lot of good examples out on the inter-webs, and as many bad examples. My only advice here is to try it for yourself... see what works for you, develop a version of the patterns that suits you best and try to keep things consistent for maintainability.
For organising all these tiers and layers in VS, I recommend trying to keep all your independent tiers/layers in their own Solution Folders (r-click the Solution, Add New Solution Folder), or in some cases (larger projects) there own solutions and preferably an automated build service to update dependent projects with up to date assemblies as required. Again, a broad subject and totally down to personal preference. Just keep an eye out when designing your application for potential upcoming Circular References.
So, I'm afraid that doesn't even slightly answer your question, but hopefully provides you with some resources to check out and a few hours of reading.
Good luck!
MVC sets up clear distinction between Model, View and Controller.
For the model, now adays, web frameworks provides ability to map the model directly to database entities (ORM), which, IMHO, end up causing performance issues at runtime due to direct database I/O.
The thing is, if that's really the case, why model ORM is so pupular and every web frameworks want to support it either organically or not.
To a web site has huge amount of traffic, it definitely won't work. But what's the work around? Connect directly to database is definitely not a wise solution here.
What's your question?
Is it a good idea to use direct db access from webpages?
A: No.
Is it a good idea to use ORM's?
A: Debatable : See How can I design a Java web application without an ORM and without embedded SQL
Is it a good idea to use MVC model?
A: Yes - it has nothing to do with "Direct" database access - it's about separating your application logic from your model and your display. (Put simply).
And the rationale for not putting database logic inside webpages has nothing to do with performance - it's about security/maintainability etc etc. Calling a usp from a webpage is likely to be MORE performant than using an ORM, but it's bad because the performance gain is negligible, and the cons are significant.
As to workaround: if you mean how do you hook up a database to a web application...?
The simplest way is to use something like Entity Frameworks or Linq-Sql with your Model - there are plenty of examples of this in tutorials on the web.
A better method IMO, is to have a separate Services layer (which may be WCF based), and have all the database access inside that, with DTO's transferring the data to your Web Application which has it's own ViewModel.
Mvc is not about orm but about separation of display logics and business logics. There is no reason your exposed model needs to be identical to you database model and many reasons to ensure that the exposed model closely matches what is to be displayed.
The other part of the solution to scale well would be to implement caching in the control and be able to distribute load on sevaral instances.
I think #BonyT has given a good answer, (and I've voted for it :) ), I'd just add that:
"web frameworks provide the ability to map the model directly to database entities (ORM), which, IMHO, ends up causing performance issues at runtime due to direct database I/O"
Even if this is true, using an ORM can solve a lot of problems with a model being easy to update and translate back and forth between a database. Solving a performance hit by buying extra web servers or cloud instances is much cheaper than having to buy extra developers or extra hours in development to solve things other people have already written ORMs to do for you.