Ninject with Fluent NHibernate within the Repository Layer - nhibernate

Due do LinqToSql not being appropriate for Many To Many relationships I am in the process of deciding to move to NHibernate (Fluent NHibernate) unless convinced otherwise...
Project Structure: UI (Mvc2 app with Ninject wiring up all services to controllers, and repositories to services), DomainServiceLayer (all util, helpers, services, domain model etc) and my Repository Layer for persistence. I have a another project call Model which basically exposes the entities, which all projects reference.
Basically I am creating my mappings within the Repository Layer with references to NHIbernate and Fluent NHIibernate, I hope to expose the interfaces to the Domain Service for querying and persisting data. How do I wire up the iSession, where do I wire it up? Any example code, what project should I put it in? Ideally I want to keep this within the Repository Layer... Is it worth learning NHibernate and going through all this?

I recommend looking at the blog posts of Bob. He describes in detail how to use the repository pattern in Ninject using NHibernate. I planned adding an example in the near future to the sample application comming with the MVC exptension as this question comes up again and again.
http://blog.bobcravens.com/2010/06/the-repository-pattern-with-linq-to-fluent-nhibernate-and-mysql/
http://blog.bobcravens.com/2010/07/using-nhibernate-in-asp-net-mvc/
http://blog.bobcravens.com/2010/09/the-repository-pattern-part-2/

Typically I have an NHibernateSessionFactory which is a singleton that has an OpenSession method and I bind ISession typically like this.
Bind<ISession>().ToMethod(context =>
NHibernateSessionFactory.Instance.OpenSession()).InRequestScope();
This method just calls through to ISessionFactory.OpenSession
You can put this into a NinjectModule in your repository layer, which your app can load when it creates the Kernel.

I do the configuration in the Application Layer (i.e. the top layer) as the configuration differs between applications. But it can be useful to break out some of the configuration into classes stored in the Repository Layer.
I open and close the session with an HttpModule.

Related

What is the path forward for changetracking complex entity relationships if Self Tracked Entities are not recommended anymore?

I have been using EF since it first came out. Used to hand build POCOs in 3.5 and was glad to see Self Tracked Entities(STE) in EF4.0.
I have use STEs in a couple of very large projects(500+ entities, some with multiple models). In these projects I use a generic Repository and a generic Unit of Work to persist the entities i.e. 2 small generic classes no mapping. By electing a core entity as the "aggregrate root", other entities are added and updated on the client side and the core entity graph containing these changes is sent to the WCF service and used in the Logic Layer which creates the Repository<[core entity]> and uses the UnitOfWork<[core entity]>.Save(Repository<[core entity]>) to persist the STEs and their children to the database.
Now Microsoft is recommending that we not use STEs. See this article
So my question is, What is(are) the patterns that are now recommended by Microsoft for applications that are persisting client changes to WCF Services that use EF?
I created a EF5 Model and examined the generated code. The there are no attributes for a WCF Service i.e. DataContract, DataMember etc
EF4 had a "ADO.NET DbContext Generator with WCF Support" template, but there isn't a EF5 equivalent.
One site suggested I should use a partial class file and decorate the same properties in that file with these attributes. But unless .net 4.5 has introduced partial properties, I cannot see how that can be done.
Another blog suggested using DTO and Automapper, which means more mapping which is error prone; especially when entity fields change type.
So now that DBContext generated code classes are not Service enabled, does this mean that we need to write another set of classes (POCOs) that:
needs to be mapped FROM the DBContext generated code classes after querying the database.
holds the data state for the WCF Service client(s)
is updatable by that client(s)
is mapped by the client(s)
has the ability to hold changed state so this can be sent back to the WCF Service
needs to be mapped TO the DBContext generated code classes for persistence
It seems we just took a great leap backwards to EF3.
If you code both client and service that runs on your hardware, you don't need to be concerned about data structures at the client as they belong to you.
If you also need to expose some of your service methods to non.NET clients you should do the 5 points above for those services anyway and use DTOs and Automapper in those occasions.These should be in a different WCF Service but implemented against the same Logic Layer, after mapping.
But how many of these type of non.NET client services are be created in the day to day building of web applications in most software teams?
This latest recommendation is confusing as it has not been explained as to WHY STEs are ALWAYS ill-conceived and what now, are the recommended patterns to be used for persisting client changes to WCF Services that use EF.
Can anybody inform me where I can find a good resource that solves this architectural design issue?
P.S.
Please don't recommend WCF Data Services or WCF RIA as we need a lot of control over how your data is retrieved and saved by clients.
Please don't recommend Code First as we use Database First as we want to have and need to control the structure of that database and not have to generated for us.
Ok so i thought the same thing when I first read this article, it seems a bit weird to deprecate a whole branch of EF like this and the intention wasn't terribly well communicated (IMO). I think a couple of things are important here:
STEs as referred to in this article refer to object context based self tracking entities (which act a little like autonomous contexts)
ObjectContext is generally being moved away from in favor of the cleaner DbContext structure (this is for both DB first and Code First)
STEs != DB first generation, you can still use an EDMX model in EF and this isn't likely to change.
When i originally saw this article I mistook STEs for POCO Proxy entities which are still available and AFAIK there are no plans to deprecate. (these achieve a similar technical solution to the problem of change detection but with a nicer interface. Check out this article for the differences EF4: Difference between POCO , Self Tracking Entities , POCO Proxies
So what does this all mean
Basically STEs in terms of the old implementation of a change tracker are being deprecated in favor of the newer forms of change tracking (Snapshot or POCO Proxies). This means that if snapshot tracking doesn't suit you you should look into POCO Proxies which are similar to the old STEs.
You can still use all previous techniques for context generation (DB First, Model First, Code First, and DB-> Code)

NHibernate 3.2 elegant IoC of mapping by code

Now that I have a good handle on NHibernate 3.2 I now feel ready to use it in anger. What I need now is an ellegant way to inject the mappings I want from an IoC container like castle windsor or the like.
The project that I am working on requires 2 sets of mappings, one to a legacy database that needs to stay put for now and one to the new schema designed to replace the old database at some point in the future. Baring in mind that I am using mapping by code rather than xml mapping.
So at a controller/middle tier level you'd be injecting a repository that implements your ISomethingRepository interface and as a parameter into that repository somehow passing a collection of ClassMapping objects.
Any ideas about the best way to go about this would be appreciated. I'm interested in the general architecture which is why I'm not specifying an IoC container.
Why not have a SessionFactoryFactory which consumes a ConfigurationGenerator.

Sharing Entity Framework models with other projects using MEF

I am currently developing a Windows service and I am am looking to use MEF to compose all of the services components at run time. The data access module (project) is using Entity Framework 4.1 and a Domain Service Class to perform CRUD operations on the entity model.
The problem I have is how to share the models outside the DAL project when composing the DAL into the worker class in the main project.
For exmaple this is one of the methods in the DAL contract interface
Function GetInspectionFaults() As IQueryable(Of InspectionFault)
This interface is currently in the DAL project (not the shared/referenced project containing the other contract interfaces) as it needs references to the entity model for the POCO types.
How do I shared these POCO types?
Phil
Although it might be a bit more work, you might want to consider having a separate set of models (view models if you will) that you have in a shared assembly (maybe a common/contracts assembly). This would enable your parts to utilise a common set of types which are not explicitly dependent on your DAL.
In regards to separation of concerns, I wouldn't recommend exporting your DAL directly, but provide an abstraction to it via something like the Repository pattern. A repository will handle the communication with the DAL and mapping from your domain to your view models.
You can export and import your repository wherever you need it, which means your parts are not dependent on a specific data source. This makes your code more robust, and more testable.

Mapping Entity Framework auto generated entities to Data Transfer Objects?

Using Entity Framework 4.1 what is the best way to map an auto generated entity framework entity to an object suitable for Data Transfer?
What i'm working with looks like this:
WPF Application -> WCF Service -> Entity Framework (DAL) -> Database
The WPF application could be swapped out to an ASP.NET website at some point in addition to the WPF Application. Hence the use of a WCF service.
The WCF Service, Database and Entity Framework code will all sit on the same physical tier.
In previous versions of Entity Framework (Before 4.0) I believe you had to write your own mapping code for your classes. Is there a better way to do this now?
Also an additional question is would it be bad practice to include methods on the DTO's that performs business logic? Where would be the best place to apply business logic in this case?
The best way to map from EF entities to DTOs is to project. My example linked there uses view models rather than DTOs, but the idea is the same.
With most ORMs, EF included, there is a cost to materializing entities which you don't need to pay if you just need a DTO. The cost includes:
Fixup -- when two objects reference the same related object, make sure they point to the same instance.
Tracking -- overhead for tracking the instance in a context.
Unnecessary columns -- you might not need all properties for your DTOs.
Aggregates -- functions like .Count() are far more efficient in SQL than in object space.
If you use a L2E projection, you don't incur any of this cost. If you follow the common advice to use the AutoMapper hammer for every problem which looks like a nail, you pay all of it.
I do agree with #sternr about not putting methods on entities / DTOs. For a more detailed examination of this idea, read "At the Boundaries, Applications are Not Object-Oriented."
Use AutoMapper to map between simple DTO's and EF entities
[EDIT:] for your other questions:
For the mapping: you could either use the built in edmx designer which allows you to use an existing DB schema to generate your model entities, or the other way around (define your entities, and let EF create your DDL).
Newer versions (as of 4.1) you could simply code your entities and add DataAnnotations on the associated properties and EF will do the magic mapping (here's a good sample)
As for adding logic to DTO's, well DTO's by their definition are a data contact - the consumer will probably create it's own implementation of them (be them by the automatic proxy or other manual wrappers), so placing logic in them kinda makes no sense.

Implementing repositories using NHibernate and Spring.Net

I'm trying to get to grips with NHibernate, Fluent NHibernate and Spring.
Following domain-driven design principals, I'm writing a standard tiered web application composed of:
a presentation tier (ASP.Net)
a business tier, comprising:
an application tier (basically a set of methods made visible to UI tier)
repository interfaces and domain components (used by the application tier)
A persistence tier (basically the implementation of the repository interfaces defined in the business tier)
I would like help determining a way of instantiating an NHibernate ISession in such a way that it can be shared by multiple repositories over the lifetime of a single request to the business tier. Specifically, I would like to:
allow the ISession instance and any transaction to be controlled outwith the repository implementation (perhaps by some aspect of the IOC framework, an interceptor?)
allow the ISession instance to be available to the repositories in a test-friendly manner (perhaps via injection or trough some shared 'context' abstraction)
avoid any unnecessary transactions being created (i.e. when only read-only operations have been executed)
allow me to write tests that use SQLLite
allow me to use Fluent NHibernate
allow the repository implementation to remain ignorant of the host environment. I don't yet know if the businese tier will run in-process with the presentation tier or will be hosted separately under WCF (in IIS), so I don't want to bind my code too closely to a HTTP context (for example).
My first attempt to solve this problem had been using the Registry pattern; storing the ISession instance in a ThreadStatic property. However, subsequent reading has suggested that isn't the best solution (as ASP.Net can switch the thread within the page lifecycle, I believe).
Any thoughts, part solutions, pattern names, pointers to up-to-date samples (NHibernate 2) will be most gratefully received.
I have not used Spring.NET so I can't comment on that. However, the rest sounds remarkably (or perhaps not so remarkably; we're hardly the first to implement these things ;) similar to my own experience. I too had trouble finding a One True Best Practice so I just read as much as I could and came up with my own interpretation.
In my situation I wanted transaction/session management to be external to the repository as well as keep repository concerns from bubbling up out of them (i.e. the code using the repository should not need to know that it's using NHibernate internally and shouldn't need to know anything about NHibernate session management). In my case it was decided that transactions would be created by default lest developers forget them, so I had to have a read-only escape mechanism. I went with the Unit of Work pattern with the NHibernate ISession instance store inside. Calling code (I also created a DSL interface for the UoW) might look something like:
using (var uow = UoW.Start().ReadOnly().WithHttpContext()
.InNewScope().WithScopeContext(ScopeContextProvider.For<CRMModel>())
{
// Repository access
}
In practice, that could be as short as UoW.Start() depending on how much context is already available. The HttpContext part refers to the storage location for the UoW which is, unsurprisingly, the HttpContext in this case. As you mentioned, for a ASP .NET application, HttpContext is the safest place to store things. ScopeContextProvider basically makes sure the right data context is provided for the UoW (ISession instance to the appropriate database/server, other settings). The "ScopeContext" concept also makes it easy to insert a "test" scope context.
Going this route makes the repositories explicitly dependent on the UoW interface. Actually, you might be able to abstract it some but I'm not sure I see the benefit. What I mean is, each repository method retrieves the current UoW instance and then pulls out the ISession object (or simply a SqlConnection for those methods that don't use NHibernate) to run the NHibernate query/operation. This works for me though because it also seems like the ideal time to make sure that the current UoW is not read-only for methods that might need to run CRUD.
Overall, I think this is one approach that solves all your points:
Allows session management to be external to the repository
ISession context can be mocked or pointed at a context provider for a test environment
Avoids unnecessary transactions (well, you'd have to invert what I did and have a .Transactional() call or something)
I can't see why you couldn't test with SQLite since that's more of an NHibernate concern
I use Fluent NHibernate myself
Allows the repository to be ignorant of the host environment (that is, the repository caller controls the UoW storage context)
As for the UoW implementation, I'm partially kicking myself for not looking around more before I started. There's a project called machine.uow which I understand is fairly popular and works well with NHibernate. I haven't played with it much so I can't say if it solves all my requirements as neatly as the one I wrote myself, but it might have saved development time as well.
Perhaps we'll get some comments as to where I went wrong or how to improve things, but I hope this is at least helpful in some way.
For reference, the software stack I'm using is:
ASP.NET MVC
Fluent NHibernate on top of NHibernate
Ninject for dependency injection
What you are describing is supported by the Spring.NET framework almost out of the box. Only for FluentNHibernate you need to add a custom SessionFactory (not a lot of code, look here:Using Fluent NHibernate in Spring.NET) to Spring.NET.
Every repository can use the same ISession, just inject the SessionFactory in your repositories and use Spring.NET's transaction services.
Just try it out, they have pretty thorough documentation imho.