Should I use Castle Windsor because NHibernate is using it, and I'm already using NHibernate? - ioc-container

I've just finished converting a large amount of legacy code to use NHibernate. The next thing I want to do is introduce an IOC container for hooking up the data access layer repositories and other such things. There are a variety of options out there at the moment - Castle Windsor, StructureMap, NInject, Unity etc; the choice is difficult.
Should I let the fact that NHibernate is already using Castle Windsor influence my decision?
I can imagine some potential benefits - for example lower memory usage. But there may be downsides, such as having to stick with the version of Castle that NHibernate is compiled against, rather than being able to upgrade the IOC container when I choose.
Thoughts?

NHibernate doesn't use any IOC container. It uses the Castle.DyanmicProxy project for creating proxy objects to facilitate lazy-loading (although this can be replaced with LinFu or your own proxy factory if you like).
You can use whichever IOC container you think most suited to you, your team and your requirements.
One point in favour of Castle Windsor is that there is already an NHibernate facility which takes care of session and transaction management for you.

Don't Use Castle IOC with Nhibernate. There are multithreading problems with Sessions of SessionFactory and IOC realization itself. We failed a large project because of this hidden architecture problem. Use Spring IOC or other IOC.
Castle is light, simple, but useless.

Related

Can Castle Windsor be used to implement IDependencyResolver in ASP.NET MVC 4?

I read this article and saw many people commented that do not use Castle Windsor to implement IDependencyResolver in ASP.NET MVC3 and stick with a custom IControllerFactory. Basically my questions now are:
Do not use Castle Windsor to implement IDependencyResolver. Is this still true in ASP.NET MVC 4 ?
If 1 is the case. Can any other DI container (Unity, StructureMap) has the same problem as Castle Windsor? Can I use any alternative?
Thanks a lot
EDIT
Sounds to me that Castle Windsor should NOT be used to implement IDependencyResolver. I have decided to use some other DI container, such as StructureMap
There is no difference between MVC3 and MVC4 in regards to IDependencyResolver, other than the fact there is a separate resolver for WebAPI.
In my opinion, Mike Hadlow is a bit too caustic on this subject, and many other people have jumped on the bandwagon without truly considering why.
Yes, it's true that Castle Windsor has a specific object lifestyle (ie lifetime management object) called Pooled that often requires you to call Release on it. And when using this lifestyle, you should probably not use IDependencyResolver because it does not provide access to this Release method (although there are ways around that too).
However, I feel it's generally bad to use this lifestyle in a web application, and you should instead use the PerWebRequest lifestyle, which will automatically release objects at the end of the web request. If this is what you are using, then there is no problem with using IDependencyResolver with Castle Windsor.
Why do I think Hadlow is too caustic? Well, because he bases his entire argument on this:
"That’s right, no ‘Release’ method. You can provide a service from your IoC container, but there’s no way to clean it up. If I was going to use this in Suteki Shop, I would have a memory leak of epic proportions."
He then goes on to reference Krzysztof Koźmic's article regarding lifestyle management, but neglects to reference his followup article which I will do here:
http://kozmic.net/2010/08/27/must-i-release-everything-when-using-windsor/
Note what he says here:
"Since as I men­tioned in my pre­vi­ous post, Wind­sor will track your com­po­nent, it’s a com­mon mis­con­cep­tion held by users that in order to prop­erly release all com­po­nents they must call Release method on the container."
He goes on to talk about various other aspects as well, but in general, I don't think most people will be using Pooled or Transient objects that required disposal in a web application. And if you do, then you should know not to use IDependencyResolver then. Otherwise, you should have no problems.
I know I will probably get a lot of grief from people arguing otherwise, but I simply do not see this as the end of the world issue that people like Hadlow seem to think it is, since there are so many alternatives, and workarounds even when you do need to call Release.
Besides all this, using a lifestyle that requires calling Release means extra work for you, the developer. You now have to manage the object lifetimes and remember to dispose of objects, and failing to do so creates memory leaks. This is, essentially, nullifying the benefits of garbage collection in my opinion. I only ever use transient objects with things that do not need disposal, and I never use pooled objects.
By the way, I may be wrong, but I don't think any other container has this problem. This leads me to the conclusion that it's Windsor that is broken, rather than MVC, when every other container out there seems to not have an issue with this. Windsor likes to stubbornly hang on to its version of reality though, so YMMV.
The advice not to use IDependencyResolver is silly, because it can be used with Castle Windsor, even though the interface lacks a release method. The solution is simply to let the IDependencyResolver implementation cache each requested instance (in a cache bounded to the web request, using HttpContext.Items for instance). At the end of the web request all cached instances (usually just a few) can be released.
To be able to release all instances at the end of the web request, you should either register an Request_Ends event in the global.asax or register a HttpModule that does this.
You can call this a workaround, but not using the IDependencyResolver is not really an option, since it is too deeply integrated with MVC. Besides, other containers (such as Ninject and Simple Injector) use this same approach (using an HttpModule) to 'release' instances.
It's unfortunate though, that there isn't an official NuGet packages for omtegrating Windsor with MVC, since now you'll have to implement this yourself. All other frameworks do have such package btw. But again, it isn't that hard to implement this yourself.
Other IoC containers already show that it is possible to implement release as an implementation detail and you don't need Release as part of the IDependencyResolver contract. The MVC designers actually did the right thing by removing such method from the API.
While I agree implementing IDependencyResolver is possible and not terribly difficult.. and yes, depending on the lifestyles at play, explicitly Release()'ing may not matter... and yes, there are ways to force a Release() by caching the instance somewhere as well as other subtle tricks - I think this is alot to leave to interpretation and can be problematic and hard to track down. Understanding when Windsor is going to track an instance isn't always immediately obvious (i.e. if the component has decommission concerns vs. not, lifestyle, etc.). One of the core value-add's of IoC is to centralize the responsibility of object creation and instance management. To properly do that and have separation of concerns - you need to have an architecture that you can trust will serve you well in call scenarios and that IMO means having a iron clad answer for Release()'ing instance of all flavors. My advice is to always implement a design that will allow Release to be called - especially on roots (i.e. a Controller).
The final argument against IDependencyResolver is you have to register a number of MVC system components if you integrate at this level. That's too intimate of a dance between my app and the framework beneath it for my taste. IControllerFactory gives a much more targeted integration point, you don't have to register MVC system components and you get a Release() hook. So, unless you want to override MVC System components, I see very little reason to implement IDepedencyResolver over IControllerFactory. I see the opposite argument in fact. I personally wised up to this on this thread over here which shows both approaches.
Hope this helps

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.

why do many instances of nHibernate sample code contain Castle dlls?

I see files like Castle.DynamicProxy.dll or Castle.Core.dll or Castle.Model.dll and various others similar in projects that are supposed to be simple, noob's introduction to nHibernate. What does this Castle stuff have to do with nHibernate? Is this unadvised muddying up the waters by the tutorial authors or does nHibernate really require this sort of extra hoops jumping just to get the basics running?
NHibernate uses proxy objects to achieve lazy loading and uses the Castle DynamicProxy module. This is the reason your entity properties need to be virtual. Because NHibernate creates proxy classes that intercept calls to your properties.

Ninject with Fluent NHibernate within the Repository Layer

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.

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.