NHibernate 3.2 elegant IoC of mapping by code - nhibernate

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.

Related

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.

AutoMapper in the DAL: When to use Mapper.Reset()?

I'm using AutoMapper in a generated Data Access Layer. That works fine. It was a little confusing when using AutoMapper in another layer and realizing the mappings created in the DAL with Mapper.CreateMap<T1, T2>() were still present. I see Mapper.Reset() which will remove these however I'd rather not have to have the other layers worry about the DAL. Would the best practice be to put a Mapper.Reset() before and after my mapping operations in the DAL? Or is there a way to give these DAL mappings a non-default key to let them persist but not interfere with the use of AutoMapper in other layers?
Note: The use of AutoMapper in the DAL has some specific options such as a number of .ForMember(...) calls that my other layers should not use (without a Mapper.Reset() they would reuse these options).
AutoMapper works as a singleton/single instance. Does it really matter though?
EDIT : This may help you Using Profiles in Automapper to map the same types with different logic
If your other layers aren't worried so much about the DAL classes chances are they aren't going to be calling Map on an instance of the DAL class anyway.
If you call Reset() then your DAL classes will need to restate them when they next need to do some mapping which will add extra very unnecessary overhead.
EDIT : If you call Reset at the start of every DAL call then you can only have a single threaded Data Access strategy. If you call Reset in the middle of a mapping for another DAL project then you are going to obviously break this - so you will have to lock on every DAL method.
This is not the way to use Automapper so I would be leaning towards either looking into those profiles, or not using it all together.
ALSO : Can you post a sample code for what is wrong with having lots and lots of multiple mappings going on? Are there different mapping strategies between two types depending on where in the DAL they are being called from?

FluentNHibernate Unit Of Work / Repository Design Pattern Questions

I think I am at a impasse here. I have an application I built from scratch using FluentNHibernate (ORM) / SQLite (file db). I have decided to implement the Unit of Work and Repository Design pattern. I am at a point where I need to think about the end game, which will start as a WPF windows app (using MVVM) and eventually implement web services / ASP.Net as UI.
Now I already created domain objects (entities) for ORM. And now I don't know how should I use it outside of ORM. Questions about it include:
Should I use ORM entity objects directly as models in MVVM? If yes, do I put business logic (such as certain values must be positive and be greater than another Property) in those entity objects? It is certainly the simpler approach, and one I am leaning right now. However, will there be gotchas that would trash this plan?
If the answer above is no, do I then create a new set of classes to implement business logic and use those as Models in MVVM? How would I deal with the transition between model objects and entity objects? I guess a type converter implementation would work well here.
To answer the first part of your question, yes your business logic and validation should go in your entities. The point of NHibernate is to let you design your entities to be persistence ignorant. That means that you should, whenever possible, be designing your entities as you would if you didn't care about persistence. This isn't entirely feasible as you'll soon find out (you'll need to make your properties virtual in order to support lazy loading and if you want to use NHibernate Validator you'll be decorating your properties with validation attributes), but for the most part NHibernate does a good job of staying out of your way.
As for whether to use your entities as the models, you'll get mixed reviews on that. Ideally, you would create separate viewmodel classes and map from your entities to the viewmodel so that your views will only access to the bare minimum of information they need. This also goes a long way in preventing N+1 access issues. However, doing so is often a huge pain. Granted, there are tools like AutoMapper that will make it easier from transposing your entity properties to a viewmodel.

Where IdentityMap belongs: UnitOfWork or Repository?

If I implement some simple OR/M tool, where do I put identity map? Obviously, each Repository should have access to its own identity map, so it can register loaded objects (or maybe DataMapper is the one who registers objects in IdentityMap?).
And when I commit unit of work, I also need to access the identity map to see which entity is dirty and which is clean (or I am wrong again and there is some outer object which calls RegisterClean/RegisterDirty methods of my UnitOfWork class? Then what object does this?).
Does this mean that I should implement IdentityMap as a completely independent object which contains inner IdentityMaps for each entity type?
Really confused about how IdentityMap, Repository and UnitOfWork work all together.
With our .NET O/R Mapper, LightSpeed we placed the identity map inside the unit of work class. This has worked very well for us and feels quite natural as it effectively acts as a level 1 cache for querying purposes during the unit of work's life.
Generally, inject or somehow provide a UoW for your Repository class so that you have an effective scope and gateway to querying.
I hope that helps.

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.