How I use NHibernate with fubuMVC

I’m currently upgrading my production website to use the excellent fubuMVC framework and have been writing about my experiences with it.

One of the early needs for me was to integrate NHibernate and I wanted to do this in as simple a way as possible without extra unit of work classes or transaction/session managers.
Here’s what I came up with:

Every request, I want a new session for the entire request and I want everything within that request in a transaction that can be committed or rolled back. However not all requests will use a session, so it will be inefficient to open a new session on every single request, so I need to make that session lazy.
Let’s start with the specifications:

    [Subject(typeof(SimpleUnitOfWorkBehaviour))]
    public class when_invoked
    {
        Establish context = () =>
        {
            _sessionFactory = new Mock<ISessionFactory>();
            _fubuRequest = new Mock<IFubuRequest>();
            _innerBehaviour = new Mock<IActionBehavior>();

            _simpleUnitOfWorkBehaviour = new SimpleUnitOfWorkBehaviour(_sessionFactory.Object, 
_fubuRequest.Object) { InnerBehavior = _innerBehaviour.Object }; }; Because of = () => _simpleUnitOfWorkBehaviour.Invoke(); It should_provide_a_lazy_session_in_the_fubu_request = () => _fubuRequest.Verify(f => f.Set(Moq.It.IsAny<Lazy<ISession>>())); It should_invoke_the_inner_behaviour = () => _innerBehaviour.Verify(b => b.Invoke()); It should_not_yet_open_the_session = () => _sessionFactory.VerifyNeverHappened(f => f.OpenSession()); static SimpleUnitOfWorkBehaviour _simpleUnitOfWorkBehaviour; static Mock<ISessionFactory> _sessionFactory; static Mock<IFubuRequest> _fubuRequest; static Mock<IActionBehavior> _innerBehaviour; }

I’m specifying a new fubuMVC behaviour – SimpleUnitOfWorkBehaviour – which is injected with an NHibernate session factory and the FubuRequest via the constructor and the InnerBehaviour via a property as per the fubuMVC inner behaviour convention.
Once invoked, this behaviour should provide a lazy session in the fubu request, it should invoke the inner behaviour but, importantly it should not yet open the session.
Here’s the implementation of that:

    public class SimpleUnitOfWorkBehaviour : IActionBehavior
    {
        readonly IFubuRequest _fubuRequest;
        readonly ISessionFactory _sessionFactory;

        public IActionBehavior InnerBehavior { get; set; }

        public SimpleUnitOfWorkBehaviour(ISessionFactory sessionFactory, 
IFubuRequest fubuRequest) { _sessionFactory = sessionFactory; _fubuRequest = fubuRequest; } public void Invoke() { _fubuRequest.Set(new Lazy<ISession>()); InnerBehavior.Invoke(); } public void InvokePartial() { InnerBehavior.InvokePartial(); } }

Pretty basic (there isn’t even an actual session yet) but functional so it needs pushing with some new specifications:

    [Subject(typeof(SimpleUnitOfWorkBehaviour))]
    public class when_invoked_and_the_inner_behaviour_chain_consumes_the_session
    {
        Establish context = () =>
        {
            _transaction = new Mock<ITransaction>();
            _session = new Mock<ISession>();
            _session.Setup(s => s.BeginTransaction()).Returns(_transaction.Object);
            _session.SetupGet(s => s.Transaction).Returns(_transaction.Object);

            _sessionFactory = new Mock<ISessionFactory>();
            _sessionFactory.Setup(f => f.OpenSession()).Returns(_session.Object);

            _fubuRequest = new Mock<IFubuRequest>();
            _fubuRequest.Setup(f => f.Set(Moq.It.IsAny<Lazy<ISession>>()))
                        .Callback<Lazy<ISession>>(lazySession => _lazySession = lazySession);

            _innerBehaviour = new Mock<IActionBehavior>();
            _innerBehaviour.Setup(b => b.Invoke()).Callback(() => {var s=_lazySession.Value;});

            _simpleUnitOfWorkBehaviour = new SimpleUnitOfWorkBehaviour(_sessionFactory.Object, 
_fubuRequest.Object) { InnerBehavior = _innerBehaviour.Object }; }; Because of = () => _simpleUnitOfWorkBehaviour.Invoke(); It should_open_the_session = () => _sessionFactory.Verify(f => f.OpenSession()); It should_begin_a_transaction = () => _session.Verify(s => s.BeginTransaction()); It should_commit_the_transaction = () => _transaction.Verify(t => t.Commit()); It should_dispose_the_session = () => _session.Verify(s => s.Dispose()); static SimpleUnitOfWorkBehaviour _simpleUnitOfWorkBehaviour; static Mock<ISessionFactory> _sessionFactory; static Mock<IFubuRequest> _fubuRequest; static Mock<IActionBehavior> _innerBehaviour; static Lazy<ISession> _lazySession; static Mock<ISession> _session; static Mock<ITransaction> _transaction; }

This one is a bit more complex as it is setting up quite a few behaviours on the mocks – first it sets up the session and transaction along with the session factory providing that session when OpenSession is called.
Then there is a callback on the FubuRequest so that when the Lazy<ISession> is set, it can be captured and finally the inner behaviour is set up to consume the captured lazy session.

It should then open the session, begin a transaction, commit it and then dispose of that session.
Here’s the implementation so far:

    public class SimpleUnitOfWorkBehaviour : IActionBehavior
    {
        readonly IFubuRequest _fubuRequest;
        readonly ISessionFactory _sessionFactory;
        ISession _session;

        public IActionBehavior InnerBehavior { get; set; }

        public SimpleUnitOfWorkBehaviour(ISessionFactory sessionFactory, 
IFubuRequest fubuRequest) { _sessionFactory = sessionFactory; _fubuRequest = fubuRequest; } public void Invoke() { _fubuRequest.Set(new Lazy<ISession>(() =>
_session ?? (_session = CreateTransactionalSession()))); InnerBehavior.Invoke(); if (_session != null) { _session.Transaction.Commit(); _session.Dispose(); } } ISession CreateTransactionalSession() { var session = _sessionFactory.OpenSession(); session.BeginTransaction(); return session; } public void InvokePartial() { InnerBehavior.InvokePartial(); } }

There is no error handling yet, so it is time for a specification for that:

    [Subject(typeof(SimpleUnitOfWorkBehaviour))]
    public class when_invoked_and_the_inner_behaviour_chain_consumes_the_session_but_
something_goes_wrong { Establish context = () => { _transaction = new Mock<ITransaction>(); _session = new Mock<ISession>(); _session.Setup(s => s.BeginTransaction()).Returns(_transaction.Object); _session.SetupGet(s => s.Transaction).Returns(_transaction.Object); _sessionFactory = new Mock<ISessionFactory>(); _sessionFactory.Setup(f => f.OpenSession()).Returns(_session.Object); _fubuRequest = new Mock<IFubuRequest>(); _fubuRequest.Setup(f => f.Set(Moq.It.IsAny<Lazy<ISession>>())) .Callback<Lazy<ISession>>(lazySession => _lazySession = lazySession); _exception = new Exception(); _innerBehaviour = new Mock<IActionBehavior>(); _innerBehaviour.Setup(b => b.Invoke()).Callback(() => { var s = _lazySession.Value; throw _exception; }); _simpleUnitOfWorkBehaviour = new SimpleUnitOfWorkBehaviour(_sessionFactory.Object,
_fubuRequest.Object) { InnerBehavior = _innerBehaviour.Object }; }; Because of = () =>
_caughtException = Catch.Exception(() => _simpleUnitOfWorkBehaviour.Invoke()); It should_rollback_the_transaction = () => _transaction.Verify(t => t.Rollback()); It should_dispose_the_session = () => _session.Verify(s => s.Dispose()); It should_not_swallow_the_problem = () => _caughtException.ShouldEqual(_exception); static SimpleUnitOfWorkBehaviour _simpleUnitOfWorkBehaviour; static Mock<ISessionFactory> _sessionFactory; static Mock<IFubuRequest> _fubuRequest; static Mock<IActionBehavior> _innerBehaviour; static Lazy<ISession> _lazySession; static Mock<ISession> _session; static Mock<ITransaction> _transaction; static Exception _exception; static Exception _caughtException; }

This specification has the same kind of setup yet this time the inner behaviour has changed to not only consume the session, but to throw an exception. It should then rollback the transaction, dispose the session and not swallow the exception and let it bubble up.

Here’s the final implementation of the SimpleUnitOfWorkBehaviour:

    public class SimpleUnitOfWorkBehaviour : IActionBehavior
    {
        readonly IFubuRequest _fubuRequest;
        readonly ISessionFactory _sessionFactory;
        ISession _session;

        public IActionBehavior InnerBehavior { get; set; }

        public SimpleUnitOfWorkBehaviour(ISessionFactory sessionFactory, 
IFubuRequest fubuRequest) { _sessionFactory = sessionFactory; _fubuRequest = fubuRequest; } public void Invoke() { _fubuRequest.Set(new Lazy<ISession>(() =>
_session ?? (_session = CreateTransactionalSession()))); try { InnerBehavior.Invoke(); if (_session != null) _session.Transaction.Commit(); } catch (Exception) { if (_session != null) _session.Transaction.Rollback(); throw; } finally { if (_session != null) _session.Dispose(); } } ISession CreateTransactionalSession() { var session = _sessionFactory.OpenSession(); session.BeginTransaction(); return session; } public void InvokePartial() { InnerBehavior.InvokePartial(); } }

Finally, I need to think about how this lazy session will be consumed – I want a delegate to the session rather than anything else knowing about the laziness of the session, so I’m going to use a http scoped Func<ISession> that is injected into any instance that needs a session.

So I need to set up the container accordingly:

 
    public class ContainerConfigurer : IConfigureContainers
    {
        public ContainerConfigurer()
        {
            Configuration = x =>
            {
                x.Scan(i =>
                {
                    i.TheCallingAssembly();
                    i.AssemblyContainingType<UserVerifier>();
                    i.SingleImplementationsOfInterface();
                });

                x.For<Func<ISession>>().HttpContextScoped().Use(
c => () => c.GetInstance<IFubuRequest>().Get<Lazy<ISession>>().Value);
x.For<ISessionFactory>().Singleton().Use(
c => c.GetInstance<ISessionFactoryCreator>().CreateFactory("Xerces"));
x.For<ISessionFactoryCreator>().Singleton().Use<SessionFactoryCreator>(); }; } }

I’m registering a delegate for an ISession that when invoked will get the current IFubuRequest and obtain the current Lazy<ISession> value, thus opening the session and providing it on demand for that current request.

So there it is a simple unit of work behaviour for fubuMVC that defers the opening of the session until needed.

(Note that this does not work if I have a singleton instance that consumes the Func<ISession> as the resolution inside the delegate will be in the wrong nested scope. However I personally always ensure that singleton state is kept outside of data providers that need the session - the data providers themselves are transient and can be injected with singleton caches for example).

Here’s a simple example of that delegate in use:

    public class UserObtainer : IObtainUsers
    {
        readonly Func<ISession> _sessionProvider;

        public UserObtainer(Func<ISession> sessionProvider)
        {
            _sessionProvider = sessionProvider;
        }

        public User ObtainUserFromEmailAddress(string emailAddress)
        {
            var session = _sessionProvider();

            return session.CreateCriteria<User>()
                .Add<User>(u => u.EmailAddress == emailAddress)
                .UniqueResult<User>();
        }
    }

Posted at at 6:42 PM on Thursday, September 22, 2011 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: , ,

How I removed magic strings from my fubuMVC redirection policy

In my previous post on my experiences with fubuMVC I had implemented a redirection policy but was not too happy with the magic strings needed within my convention to point at the methods on my home controller.

Here’s what I currently have:

    public class PermanentRedirectionConvention : IConfigurationAction
    {
        public void Configure(BehaviorGraph graph)
        {
            graph.Behaviors
                .Where(c => c.FirstCall().HandlerType == typeof(HomeController)
                            && c.FirstCall().Method.Name.ToLower() == "news")
                .Each(c => c.Prepend(new Wrapper(typeof(PermanentNewsRedirectionBehaviour))));

            graph.Behaviors
                .Where(c => c.FirstCall().HandlerType == typeof(HomeController)
                          && c.FirstCall().Method.Name.ToLower() == "about")
                .Each(c => c.Prepend(new Wrapper(typeof(PermanentAboutRedirectionBehaviour))));
        }
    }

Above, I am using the FirstCall() method to retrieve the ActionCall and examining the handler type and method info to establish if it meets my criteria.

To improve this I need an extension method on the ActionCall that will let me point at a method on it’s HandlerType, so this argument will need to be an Expression<Action<THandlerType>> :

    public static class BehaviourExtensions
    {
        public static bool MatchesHandler<THandlerType>(this ActionCall actionCall, 
                                     Expression<Action<THandlerType>> handlerExpression)
        {
            var methodCallExpression = handlerExpression.Body as MethodCallExpression;
            if(methodCallExpression==null)
                throw new Exception("Expected a method call expression");

            return typeof(THandlerType) == actionCall.HandlerType 
                   && methodCallExpression.Method == actionCall.Method;
        }
    }

This new extension method returns the match between the generic THandlerType and the ActionCall’s HandlerType and also the method from the method call expression against the ActionCall’s method.

This now enables me to remove my magic strings:

    public class PermanentRedirectionConvention : IConfigurationAction
    {
        public void Configure(BehaviorGraph graph)
        {
            graph.Behaviors
                .Where(c => c.FirstCall()
.MatchesHandler<HomeController>(controller => controller.News())) .Each(c => c.Prepend(new Wrapper(typeof(PermanentNewsRedirectionBehaviour)))); graph.Behaviors .Where(c => c.FirstCall()
.MatchesHandler<HomeController>(controller => controller.About())) .Each(c => c.Prepend(new Wrapper(typeof(PermanentAboutRedirectionBehaviour)))); } }

Posted at at 6:34 PM on Tuesday, September 13, 2011 by Posted by Justin Davies | 0 comments Links to this post   | Filed under:

How I improved my fubuMVC redirection policy with a convention

In the previous post of this fubuMVC series, I showed how I had implemented permanent redirection for a url using fubuMVC. I had enriched the action call for the old route with a behaviour that issues a permanent redirection and this behaviour occurred after the action call.

In this post I’m going to illustrate how I gained more control over where the behaviour was added – to do this I wrote a convention that implements IConfigurationAction and hooked this into the fubuMVC registry.

    public class PermanentRedirectionConvention : IConfigurationAction
    {
        public void Configure(BehaviorGraph graph)
        {
            graph.Behaviors
                .Where(c => c.FirstCall().HandlerType == typeof (HomeController)
                            && c.FirstCall().Method.Name.ToLower() == "news")
                .Each(c => c.Prepend(new Wrapper(typeof (PermanentNewsRedirectionBehaviour))));

            graph.Behaviors
                .Where(c => c.FirstCall().HandlerType == typeof (HomeController)
                          && c.FirstCall().Method.Name.ToLower() == "about")
                .Each(c => c.Prepend(new Wrapper(typeof(PermanentAboutRedirectionBehaviour))));
        }
    }

When you implement a convention you are given the behaviour graph so that you can amend it as you see fit.
Here I am filtering the IEnumerable<BehaviorChain> on the graph, called “Behaviors”, and looking for the one that represents the HomeController and “news” method.
Once I have the behaviour chain that corresponds to this action I am going to ensure that this behaviour sits at the top using the Prepend method.
I’ve also done the same for another action that I am permanently redirecting.

In order to plug this into my fubu registry I am going to replace the policies enrichment with my convention instead:

    public class XercesFubuRegistry : FubuRegistry
    {
        public XercesFubuRegistry()
        {
            IncludeDiagnostics(true);

            Applies.ToThisAssembly();

            Actions.IncludeClassesSuffixedWithController();

            Routes.HomeIs<HomeController>(c => c.FrontPage())
                    .IgnoreControllerNamespaceEntirely()
                    .UrlPolicy<EnsureControllersCanHaveARootUrlPolicy>();

            ApplyConvention<PermanentRedirectionConvention>(); <-- new line

            this.UseSpark();

            Views.TryToAttachWithDefaultConventions();
        }
    }

This leaves me with a different behaviour graph from last time where my own behaviour is above the action call:

redirectchain2

This now enables me to amend my HomeController to better reflect the fact that the news and action methods should never be called:

    public class HomeController
    {
        public HomeViewModel FrontPage()
        {
            return new HomeViewModel();
        }

        public AutomaticRedirection News()
        {
            throw new Exception("Automatic redirection should have occurred 
                                                before reaching this method");
        }

        public AutomaticRedirection About()
        {
            throw new Exception("Automatic redirection should have occurred
                                                before reaching this method");
        }
    }

    public class HomeViewModel { }

    public class AutomaticRedirection { }

There’s my redirection policy implemented – there are a couple of things I would like to review though…

The first is that its a shame that I have to have “placeholder” actions in order to point to them in my conventions but by nature of the behaviour graph being built up front we no longer have the dynamic resolution of routes and actions (and that is a good thing for more deterministic and testable behaviour).
I did look at how we might add permanent redirection into fubuMVC itself, but it meant adding behaviour chains that have no action calls and outputs and was not a quick feat, so have not pursued that yet.

The second point is the “magic strings” I’m using in the convention itself for the method names – I don’t like magic strings.
In my next post I’ll show how I removed those and tightened the implementation.

Posted at at 7:35 AM on Tuesday, September 6, 2011 by Posted by Justin Davies | 0 comments Links to this post   | Filed under:

How I permanently redirect using fubuMVC

In the process of migrating to fubuMVC I’ve previously touched upon a change in urls in one of my previous posts on my experiences with fubuMVC.
In this process I have changed the urls for my static pages from “/home/news” to “/news” for instance and this means that I now have to deal with permanent redirections and issuing 301 redirects for the original urls.

With fubuMVC, I’m going to achieve this with a custom behaviour that is inserted into the behaviour chain.

(to learn more about behaviour chains there are a number of good articles out there, here’s one:
http://murrayon.net/2011/06/fubumvc-behavior-chains-bmvc-pattern.html
)

In order to write a custom behaviour that issues a response I am going to need to interact with the IOutputWriter abstraction and write a response code and custom headers to show the new location of the permanent redirect.

At the time of writing this, the IOutputWriter doesn’t yet support writing headers so I’m going to have to extend its functionality for the time being. Here’s the current interface in fubuMVC:

  public interface IOutputWriter
  {
    void WriteFile(string contentType, string localFilePath, string displayName);

    void Write(string contentType, string renderedOutput);

    void RedirectToUrl(string url);

    void AppendCookie(HttpCookie cookie);

    void WriteResponseCode(HttpStatusCode status);

    RecordedOutput Record(Action action);
  }

So here’s a simple extension which will write my header directly into the HttpResponse (normally this would be in the HttpOutputWriter concrete class, but I’m extending the interface for my own project here, so don’t have much choice but to place it there; perhaps we can get it added to fubuMVC very soon).

  public static class OutputWriterExtensions
  {
        public static void WriteHeader(this IOutputWriter outputWriter, 
                        string headerName, string headerValue)
        {
            HttpContext.Current.Response.AppendHeader(headerName, headerValue);
        }
  }

I’m also going to wrap the writing of the response code and the header generation into a specific method, again an extension. I also need to send the IEndpointService in the method call because it is an extension method.
Here’s the wrapper:

    public static class OutputWriterExtensions
    {
        public static void WritePermanentRedirectTo<T>(this IOutputWriter outputwriter, 
                Expression<Action<T>> actionExpression, IEndpointService endpointService)
        {
            var endpoint = endpointService.EndpointFor(actionExpression);
            outputwriter.WriteHeader("Location", endpoint.Url);
            outputwriter.WriteResponseCode(HttpStatusCode.MovedPermanently);
        }
    }

This now enables me to point at a method on an action and permanently redirect to it.

Now for the behaviour itself – I’m going to inherit from BasicBehavior which does most of the heavy lifting for me leaving me to override the perform invoke method:

    public class PermanentNewsRedirectionBehaviour : BasicBehavior
    {
        private readonly IOutputWriter _outputWriter;
        private readonly IEndpointService _endpointService;

        public PermanentNewsRedirectionBehaviour(IOutputWriter outputWriter, 
                                                 IEndpointService endpointService) 
          : base(PartialBehavior.Ignored)
        {
            _outputWriter = outputWriter;
            _endpointService = endpointService;
        }

        protected override DoNext performInvoke()
        {
            _outputWriter.WritePermanentRedirectTo<NewsController>(c => c.Root(), 
                                                                   _endpointService);
            return DoNext.Stop;
        }
    }


This is a behaviour that will redirect to the news action using the new extension method I’ve written for the output writer.
The simplest way of putting this into my fubuMVC registry is to use the “EnrichCallsWith” functionality for policies:

    public class XercesFubuRegistry : FubuRegistry
    {
        public XercesFubuRegistry()
        {
            IncludeDiagnostics(true);

            Applies.ToThisAssembly();

            Actions.IncludeClassesSuffixedWithController();

            Routes.HomeIs<HomeController>(c => c.FrontPage())
                    .IgnoreControllerNamespaceEntirely()
                    .UrlPolicy<EnsureControllersCanHaveARootUrlPolicy>();

            Policies.EnrichCallsWith<PermanentNewsRedirectionBehaviour>(call => 
                call.HandlerType == typeof(HomeController) &&
                call.Method.Name.ToLower() == "news");

            this.UseSpark();

            Views.TryToAttachWithDefaultConventions();
        }
    }

The new part of the registry code above is the Policies section where I am enriching a call to the HomeController for a “news” method, a new one as a placeholder for this redirection:

    public class HomeController
    {
        public HomeViewModel FrontPage()
        {
            return new HomeViewModel();
        }

        public AutomaticRedirection News()
        {
            return new AutomaticRedirection();
        }
    }

    public class HomeViewModel
    {}

    public class AutomaticRedirection
    {}

I’ve created a new class called AutomaticRedirection just as another placeholder to indicate what will happen for this method.
In order to see this new functionality I can look at another part of the fubuMVC diagnostics – the behaviour chain and the specific chain for the “home/news” route:

redirectchain 

I now have permanent redirection in place and baked into fubuMVC in the way that I want it to.
By enriching this action, the action call will occur first and then the wrapper takes effect and permanently redirects - all requests to “home/news” now 301 redirect to “news”.

In the next post I will show how a custom convention that implements IConfigurationAction can instead give me more fine grained control over where the behaviour is inserted in the graph.

Posted at at 10:23 PM on Thursday, September 1, 2011 by Posted by Justin Davies | 0 comments Links to this post   | Filed under: