Thursday, March 15, 2012

Creating a FubuMVC Behavior

As part of the day Job, our company decided to use FubuMVC for one of our monitoring and administration tools. This was all very exciting as I enjoy playing with new and shiny things. It's been a few days now and in an effort to put something back to the community I thought I'd provide you all with a few things I've learnt that might help someone out one day. I'll be demoing 3 things

Why would you want to create your own FubuMVC behaviour?

I like to think of the behaviours as a bit like the decorator pattern. They allow us to follow the Open/Closed principle in SOLID. I.e. I can add things such as

  • Logging
  • exception handling
  • unit of work
  • validation

to a code base without actually modifying the existing handler. It's one of the reasons I was so keen to try out FubuMVC. There are a few existing blog posts I've found which explain how to create a FubuMVC behaviour:

I'm going to show you how to create a transaction wrapping behaviour or unit of work behaviour, which is more simplistic that Justin Davies post

Get with the code already

My breif was to make sure that all request handlers than use an ISession are wrapped in a transaction.

First you need to create a behaviour

public class TransactionBehaviour : IActionBehavior
{
    private readonly ISession session;
    public IActionBehavior InnerBehavior { get; set; }

    public TransactionBehaviour(ISession session)
    {
        this.session = session;
    }

    public void Invoke()
    {
        using (var transaction = session.BeginTransaction())
        {
            InnerBehavior.Invoke();
            transaction.Commit();
        }
    }

    public void InvokePartial()
    {
        Invoke();
    }
}

Then you need to tell FubuMVC when and how to apply the behaviour using the following code:

public class TransactionBehaviourConfiguration : IConfigurationAction
{
    public void Configure(BehaviorGraph graph)
    {
        GenericEnumerableExtensions.Each<ActionCall>(graph.Actions()
                                    .Where(x => x.HandlerType.HasInjected<ISession>()), x => x.AddBefore(new Wrapper(typeof(TransactionBehaviour))));
    }
}

public static class TypeExtensions
{
    public static bool HasInjected<T>(this Type type)
    {
        return
            type
                .GetConstructors()
                .Any(x => x.GetParameters()
                                .Any(y => y.ParameterType.IsAssignableFrom(typeof (T))));
    }
}

Then you include the convention above in the FubuMVC Registry:

public class ConfigureFubuMVC : FubuRegistry
{
    public ConfigureFubuMVC()
    {
        IncludeDiagnostics(true);
        Routes.HomeIs<GetInputModel>();
        Views.TryToAttachWithDefaultConventions();
        ApplyHandlerConventions(typeof(HandlersMaker));
        this.UseSpark();

        ApplyConvention<TransactionBehaviourConfiguration>();  // New Line
    }
}

Lastly, as I'm injecting the ISession into my handler like this:

public class PostHandler
{
    private readonly ISession session;

    public PostHandler(ISession session)
    {
        this.session = session;
    }

    public FubuContinuation Execute(PostInputModel inputModel)
    {
        var customer = new Customer {Name = inputModel.Name};
        session.Save(customer);

        return FubuContinuation.RedirectTo(new ExampleRead.GetInputModel());
    }
}

I need to make sure that the ISession is kept for the whole of the http request using the Structure Map IoC container as follows:

public class TransactionBehaviourRegistry: Registry
{
    private const string DbName = @"c:\temp\example.db";

    public TransactionBehaviourRegistry()
    {
        ForSingletonOf<ISessionFactory>().Use(CreateSessionFactory);
        // Keep ISession for whole of Http Request
        For<ISession>().HttpContextScoped().Use(x => x.GetInstance<ISessionFactory>().OpenSession());
    }

    private ISessionFactory CreateSessionFactory()
    {
        return Fluently.Configure()
                .Database(
                    SQLiteConfiguration.Standard
                        .UsingFile(DbName)
                )
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<CustomerMap>())
                .ExposeConfiguration(BuildSchema)
                .BuildSessionFactory();
    }

    private void BuildSchema(Configuration config)
    {
        // Only create once
        if (File.Exists(DbName))
            return;
        new SchemaExport(config)
            .Create(false, true);
    }
}

Now if I navigate to _fubu I can see that the handlers which have an ISession injected are now wrapped in a transaction.

Any handlers which don’t make use of ISession are not wrapped in a transaction.

Conclusion

The code for this example can be found on my git hub account here. As you can see with very little code you can add code to all the handlers which use an ISession. Good luck and let me know if I’ve done anything wrong or if you can think of any improvements. Would be great to hear your feedback.

117 comments:

  1. Hey David,

    Great post! Two quick things to note:

    1)So long as you register your dependencies transiently, the Nested Container in Fubu will do the "http request scoped" business for you.

    2) I see that you're using Advanced Diagnostics. Did you know that it also records requests? The visualizers for a request aide in understanding how the behaviors all fit together.

    Always great to see more Fubu users :)

    ReplyDelete
  2. Thanks Josh... especially for the feedback. Great to be on board. I'm really enjoying FubuMVC.. think I've only scratched the surface so far.

    ReplyDelete
  3. This may or may not apply in your situation.

    For most of our applications our transaction behavior for the InvokePartial call will just call invoke partial for the next behavior. You'll get surprising results in some cases if you don't continue with the partial path. Also in many cases on the partial path you can assume that there is already a transaction present and not need to start a second.

    Good stuff, keep 'em coming!

    ReplyDelete
  4. “using AppFunc = Func;”

    That just means that I can use the clean, easier to remember name “AppFunc” to refer to the type Func” as an alias in only that one file. I don’t use that very often, but it’s also a nice way to get around using two classes of the same name but different namespaces in the same file. I`m working on purevpn project, will let you know the results soon.

    ReplyDelete
  5. Good and nice blog post, thanks for sharing your information.. it is very useful to me.. keep rocks and updating

    Dot Net Training in chennai

    ReplyDelete
  6. This is the best place where we can get good collection of information with an ease...
    Best Online Software Training Institute | PHP Training

    ReplyDelete
  7. Very nice information and explanation about cloud computing. Thanks for sharing. keep on updating such a nice information.
    VMware Exam Centers in Chennai | VMware Exam Centers in Velachery

    ReplyDelete
  8. Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition.
    Citrix Exams in Chennai | Xenapp exam center in Chennai

    ReplyDelete
  9. Very informative blog.Thanks for sharing such good information and keep on updating.
    OCJP Exam Center in Chennai | OCJP Exam Center in Velachery

    ReplyDelete
  10. Very informative blog.Thanks for sharing such good information and keep on updating..
    VMware Exam Centers in Chennai | VMware Exam Centers in Velachery

    ReplyDelete
  11. very good information...thanks for sharing...nice blog..
    thank you
    tosca online training in hyderabad

    ReplyDelete
  12. Appreciation for really being thoughtful and also for deciding on certain marvelous guides most people really want to be aware of.

    UX Design Training
    UX Design Training in Chennai

    ReplyDelete
  13. Very very nice information and useful as well. thanks for sharing such a great information with us!
    DevOps Online Training

    ReplyDelete

  14. I found this post interesting and worth reading. Keep going and putting efforts into good things.
    DevOps Online Training

    ReplyDelete
  15. Really it was an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing.Data Science Online Training in Hyderabad

    ReplyDelete
  16. Thank You for your information
    www.bisptrainings.com

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. Very good information about DevOps clear explanation thanks for sharing
    anyone want to learn advance devops tools or devops online training visit:
    DevOps Online Training
    DevOps Training
    DevOps Training in Ameerpet

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. My favorite casino! purely top online casino I recommend to everyone!!! The engine does not slow down. I did not observe any breaks in the connection. Won $ 2200. Brought the winnings to no problem. Very beautiful, pleasant, comfortable casino. Very nice voice acting. Honesty control. In short .. all zashib

    ReplyDelete
  22. Hi, Thanks for sharing nice information it really good for reading this. Anyhave interesting to learn Digital Marketing Course in Ameerpet . Best institutes is Hyderabad Digital Marketing Institutes they provide all concepts SEO,SMM,SMO ADwords, Affiliate Marketing.

    ReplyDelete
  23. Nice post. It is very useful and informative post.

    CEH Training In Hyderbad

    ReplyDelete
  24. Excellent blog I visit this blog it's really awesome. The important thing is that in this blog content written clearly and understandable. The content of information is very informative.
    Workday HCM Online Training!
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  25. Подскажите где найти блок питания для светодиодной ленты, нашел в компании Ekodio вроде хорошие, буду тестить.

    ReplyDelete
  26. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.
    Thanks & Regards,
    VRIT Professionals,
    No.1 Leading Web Designing Training Institute In Chennai.

    And also those who are looking for
    Web Designing Training Institute in Chennai
    SEO Training Institute in Chennai
    Photoshop Training Institute in Chennai
    PHP & Mysql Training Institute in Chennai
    Android Training Institute in Chennai

    ReplyDelete
  27. Its very nice to read your blog and im really appreciate to read that.Thanks to you for giving wonderfull ideas..
    R Training Institute in Chennai | R Programming Training in Chennai

    ReplyDelete
  28. I love this post.


    โปรโมชั่นGclub ของทางทีมงานตอนนี้แจกฟรีโบนัส 50%
    เพียงแค่คุณสมัคร Gclub กับทางทีมงานของเราเพียงเท่านั้น
    ร่วมมาเป็นส่วนหนึ่งกับเว็บไซต์คาสิโนออนไลน์ของเราได้เลยค่ะ
    สมัครสมาชิกที่นี่ >>> Gclub online

    ReplyDelete
  29. Very cool!

    เว็บไซต์คาสิโนออนไลน์ที่ได้คุณภาพอับดับ 1 ของประเทศ
    เป็นเว็บไซต์การพนันออนไลน์ที่มีคนมา สมัคร Gclub Royal1688
    และยังมีเกมส์สล็อตออนไลน์ 1688 slot อีกมากมายให้คุณได้ลอง
    สมัครสมาชิกที่นี่ >>> Gclub Royal1688

    ReplyDelete
  30. A bewildering web journal I visit this blog, it's unfathomably heavenly. Oddly, in this present blog's substance made purpose of actuality and reasonable. The substance of data is informative
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  31. A bewildering web journal I visit this blog, it's unfathomably heavenly. Oddly, in this present blog's substance made purpose of actuality and reasonable. The substance of data is informative
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  32. This comment has been removed by the author.

    ReplyDelete
  33. Just now I read your blog, it is very helpful nd looking very nice and useful information.
    Digital Marketing Online Training
    Servicenow Online Training
    EDI Online Training

    ReplyDelete
  34. Hal yang paling penting dalam bermain judi ceme keliling adalah dengan mengatur emosi saat bermain. Karena emosi akan menentukan kemenangan permainan
    asikqq
    http://dewaqqq.club/
    http://sumoqq.today/
    interqq
    pionpoker
    bandar ceme terpercaya
    freebet tanpa deposit
    paito warna
    syair sgp

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. Hello, i have a question, i need your help if it's possible. I know that in order to get data from google spreadsheet you need to use a sheets api callback function.

    Is there any way to get specific data from a google spreadsheet column and pass them as variable in json feed callback function that is used globally from users in blogger platform? In other words, is it possible, except of post url, post img, post id, author img, author url and so on, querries that are available in json feed blogger api, to have additional querries from google sheets api?

    ReplyDelete
  37. Nice Post. If you wish to get study abroad in any course. The below information will suit you.
    Skolarrssolutions
    Mbbs in Russia
    Mbbs in UK
    Mbbs in Malaysia

    ReplyDelete
  38. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command
    apache spark online training

    ReplyDelete
  39. The best forum that i have never seen before with useful content and very informative.
    Pega Training
    RPA Training

    ReplyDelete
  40. I have seen your blog and really amazing information put in this. If anyone needs Website Designing and Digital Marketing Services in India, visit Ogen Infosystem in Delhi to get a creative and responsive website.
    Web Design Company in Delhi

    ReplyDelete
  41. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
    reactjs online training

    ReplyDelete
  42. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    Best Android Online Certification

    ReplyDelete

  43. Erectile dysfunction is a condition where a man is not able to get an erection. Even if they are able to get an erection, it does not last for too long. Suffering from erectile dysfunction can affect the person both physically and mentally. Therefore a person needs to take medical help to make the condition better. Also suffering from erectile dysfunction can affect the relation of the person with their partners. The medication that has brought about a wave of change in this field is the use of Viagra for erectile dysfunction. It works by targeting the basic cause of the issue thus helping millions of men all across the world. If you are a man who has been facing an issue with getting and maintaining an erection for a long time now, then you should
    .Buy Viagra online

    ReplyDelete

  44. Erectile dysfunction is a condition where a man is not able to get an erection. Even if they are able to get an erection, it does not last for too long. Suffering from erectile dysfunction can affect the person both physically and mentally. Therefore a person needs to take medical help to make the condition better. Also suffering from erectile dysfunction can affect the relation of the person with their partners. The medication that has brought about a wave of change in this field is the use of Viagra for erectile dysfunction. It works by targeting the basic cause of the issue thus helping millions of men all across the world. If you are a man who has been facing an issue with getting and maintaining an erection for a long time now, then you should
    .Buy Viagra online

    ReplyDelete
  45. You have provided a nice article, Thank you very much for this one. And I hope this will be useful for many people. And I am waiting for your next post keep on updating these kinds of knowledgeable things
    App Development Course in Chennai
    Android Development Course in Chennai
    Android Training Institutes in Bangalore
    Android App Development Course in Bangalore
    Android Course in Coimbatore
    Android App Development Course in Coimbatore
    Android Course in Madurai

    ReplyDelete
  46. Thank you for sharing such a nice and interesting blog with us. I have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information.
    Digital Marketing Training In Hyderabad
    sem training in hyderabad
    seo training in hyderabad
    SMM Training In Hyderabad

    ReplyDelete
  47. smart outsourcing solutions is the best outsourcing training
    in Dhaka, if you start outsourcing please
    visit us: graphic design training
    digital marketing training
    Seo training in dhaka

    ReplyDelete
  48. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    angular js online training
    best angular js online training
    top angular js online training

    ReplyDelete
  49. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    angular js online training

    ReplyDelete
  50. Nice! I like to share it with all my friends and hope they will also like this information.
    Power Bi Training In Hyderabad
    Power Bi Online Training
    Power Bi Training

    ReplyDelete
  51. This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points. To appreciate this I like to share some useful information.tableau training in bangalore

    ReplyDelete
  52. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    angular js online training

    ReplyDelete
  53. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    top workday studio online training

    ReplyDelete
  54. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    workday studio online training
    best workday studio online training
    top workday studio online training

    ReplyDelete