Where IdentityMap belongs: UnitOfWork or Repository? - orm

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.

Related

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.

Entity Framework - implementing IDbSet

I would like to implement IdbSet to provide my DbContext a custom implementation that will essentially serve to filter my data for the currently logged in user (I am working on a multi-tenant application). The general idea I am going with is very similar to this post: Can a DbContext enforce a filter policy?
However, it is not clear to me how to make DbContext "know" about how to use my own class that implements IDbSet. I am having a tough time finding documentation on this. Any pointers would be helpful!
TIA,
-jle
I'm almost sure that you cannot create your own implementation of IDbSet and pass it to entity framework. Such implementation will lose all stuff related to EF which is internally implemented in DbSet itself - by internally I really mean that there is no public API to replace it. IDbSet interface is provided not because it is supposed to create your own sets but because it allows mocking sets when unit testing application. The only way you can extend functionality is either:
Inheriting DbSet but I'm afraid that it will not help you as well because methods / properties will not be marked as virtual.
Creating custom IDbSet implementation which will wrap DbSet. This looks like the best chance but you can still find that DbContext doesn't like your new implementation. I gave this very quick try but I was not successful. My implementation worked for persisting but not for querying.

Repository design for complex objects?

What is the best way to design repositories for complex objects, assuming use of an ORM such as NHibernate or Entity Framework?
I am creating an app using Entity Framework 4. The app uses complex objects--a Foo object contains a collection of Bar objects in a Foo.Bars property, and so on. In the past, I would have created a FooRepository, and then a BarRepository, and I would inject a reference to the BarRepository into the FooRepository constructor.
When a query is passed to the FooRepository, it would call on the BarRepository as needed to construct the Foo.Bars property for each Foo object. And when a Foo object is passed to the FooRepository for persistence, the repository would call the BarRepository to persist the objects in the Foo.Bars property.
My question is pretty simple: Is that a generally accepted way to set up the repositories? Is there a better approach? Thanks for your help.
In domain-driven design, there is the concept of a "root aggregate" object. The accepted answer to a related question has good information on what it is and how you would use it in your design. I don't know about the Entity Framework but NHibernate does not require the usage pattern you are describing. As long as all the nested objects and their relationships are properly mapped to tables, saving the aggregate root will also save all its child object. The exception is when a nested object has specific business logic that needs to performed as part of its access or persistence. In that case, you would need to pass the "child" repositories so you are not duplicating that business logic.
Repository pattern helps grouping of business transactions among related entities. Meaning if you have two domain objects foo and bar and have a common transactions like GetList(),Update() then a common repository like FoobarReporsitory can be created. You can even abstract that to an interface called IFoobarReporsitory to make application loosely coupled.

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.

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.