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.

156 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. Very very nice information and useful as well. thanks for sharing such a great information with us!
    DevOps Online Training

    ReplyDelete

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

    ReplyDelete
  14. 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
  15. Thank You for your information
    www.bisptrainings.com

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

    ReplyDelete
  17. 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
  18. This comment has been removed by the author.

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

    ReplyDelete
  20. 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
  21. 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
  22. Подскажите где найти блок питания для светодиодной ленты, нашел в компании Ekodio вроде хорошие, буду тестить.

    ReplyDelete
  23. 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
  24. This comment has been removed by the author.

    ReplyDelete
  25. 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
  26. This comment has been removed by the author.

    ReplyDelete
  27. 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
  28. 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
  29. The best forum that i have never seen before with useful content and very informative.
    Pega Training
    RPA Training

    ReplyDelete
  30. 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
  31. 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
  32. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    Best Android Online Certification

    ReplyDelete
  33. 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
  34. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    best angular js online training
    best microservices online training
    best workday studio online training

    ReplyDelete
  35. I have seen your blog and really amazing information put in this. If anyone needs Website Designing and Digital Marketing Services in India visit the websites.

    digital-marketing-course-in-hyderabad/

    digital-marketing-agency-in-hyderabad/

    selenium-training-in-hyderabad/

    salesforce-training-hyderabad/

    microsoft-azure-training-in-hyderabad/

    ReplyDelete

  36. Thank you for sharing such a great information.Its really nice and informative.hope more posts from you. I also want to share some information recently i have gone through and i had find the one of the best mulesoft 4 training videos


    ReplyDelete
  37. "It's very useful post and i had good experience with this salesforce training in bangalore who are offering good certification assistance. I would say salesforce training is a best way to get certified on crm.

    salesforce training in marathahalli
    salesforce training india
    "

    ReplyDelete
  38. Thanks for sharing it.I got Very valuable information from your blog.your post is really very Informative.I’m satisfied with the information that you provide for me.Nice post. By reading your blog, i get inspired and this provides some useful information.

    Php training in pune at 3ri Technologies

    ReplyDelete
  39. Really Good article.provided a helpful information.keep updating...
    Regards : Best SAP FICO Training in Pune With Placement

    ReplyDelete
  40. I am inspired with your post writing style & how continuously you describe this topic. After reading your ab initio tutorial post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.

    ReplyDelete
  41. Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better! Cheers, keep doing awesome
    BCOM 1st, 2nd & 3rd Year Time Table 2020

    ReplyDelete
  42. This is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious.... data scientist training

    ReplyDelete

  43. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog,i want to share some Information about learn splunk and splunk tutorial for beginners . keep updates regularly..

    ReplyDelete
  44. I just loved your article on the beginners guide to starting a blog.

    Web designing trends in 2020

    When we look into the trends, everything which is ruling today’s world was once a start up and slowly begun getting into. But Now they have literally transformed our lives on a tremendous note. To name a few, Facebook, Whats App, Twitter can be a promising proof for such a transformation and have a true impact on the digital world.

    we have offered to the advanced syllabus course web design and development for available join now.

    more details click the link now.

    https://www.webdschool.com/web-development-course-in-chennai.html

    ReplyDelete
  45. You need to take part in a contest for one of the most useful websites on the internet. eviews I'm going to recommend this blog!

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

    ReplyDelete
  47. I blog quite often and I seriously thank you for your information. Your article has really peaked my interest. I am going to bookmark your site and keep checking for new details about once a week. I opted in for your Feed too. KBC Winner 2020

    ReplyDelete
  48. very useful tips for every user. We will provide power bi training and Selenium Tutorial Videos online by 10+ years experienced faculty.

    ReplyDelete
  49. Great article like this require readers to think as they read. I took my time when going through the points made in this article. I agree with much this information DevOps Training in Chennai | DevOps Training in anna nagar | DevOps Training in omr | DevOps Training in porur | DevOps Training in tambaram | DevOps Training in velachery

    ReplyDelete
  50. Hey Loved the post! Great article and congrats on Reaching the To 50! I will be back to visit often

    ReplyDelete
  51. cyberflix iPhone bet it is not available in 🍎 🏪 Ramky Supervisor I want you so bad that I have to talk from start to end up going out with me and my mom

    ReplyDelete
  52. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging. After seeing your article I want to say that also a well-written article with some very good information which is very useful for the AWS Online Training

    ReplyDelete
  53. 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
    Data Science Training In Bangalore

    Data Science Training

    Data Science Online Training

    Data Science Training In Hyderabad

    Data Science Training In Chennai

    Data Science Training In Coimbatore

    ReplyDelete
  54. I want to say thanks to you. I have bookmark your site for future updates.
    Digital Marketing Courses in Hyderabad With Placements

    ReplyDelete
  55. It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read more things about it!
    Best Institutes For Digital Marketing in Hyderabad

    ReplyDelete
  56. I have express a few of the articles on your website now, and I really like your style of blogging. I added it to my favorite’s blog site list and will be checking back soon…
    Best Institutes For Digital Marketing in Hyderabad

    ReplyDelete
  57. Hey, Nice one information

    Online IT Software Courses Training ICT South Bopal - Ahmedabad

    Institute of Computer Training - ICT Bopal

    ReplyDelete
  58. I was browsing through various sites and blogs and then I came across yours. It was a great blog. Here is a referred link same as yours   oracle fusion hcm training.  Thanks for sharing this with us. It really helped us to enhance our knowledge.

    ReplyDelete
  59. Thank you for sharing this article with us. It seems very useful to me. Thank You ones again!

    https://www.ahmedabadcomputereducation.com/course/php-training-course/

    ReplyDelete
  60. I just loved your article on the beginners guide to starting a blog. If somebody take this blog article seriously in their life, he/she can earn his living by doing blogging. Thank you for this article.
    Java Training in Gurgaon

    ReplyDelete
  61. Nice & Informative Blog !
    If you are looking for the best accounting software that can help you manage your business operations. call us at QuickBooks Phone Number 1-(855) 550-7546.

    ReplyDelete
  62. https://www.cambridgeinfotech.in/
    Cambridge InfoTech is Best Software Training Institute In Bangalore on AWS, Selenium, Java, DevOps, Data Science, Python, Digital Marketing.

    ReplyDelete
  63. Thank you for sharing this useful article with us. This blog is a very helpful to me in future. Keep sharing informative articles with us.
    www.djshahca.com

    ReplyDelete
  64. Thank you for sharing this useful article with us. This blog is a very helpful to me in future. Keep sharing informative articles with us.
    www.djshahca.com

    ReplyDelete
  65. Recently, I have commenced a blog the info you give on this site has encouraged and benefited me hugely. Thanks for all of your time & work. hire php web developer

    ReplyDelete
  66. Hey! Excellent work. Being a QuickBooks user, if you are struggling with any issue, then dial QuickBooks Customer Service (877)603-0806. Our team at QuickBooks will provide you with the best technical solutions for QuickBooks problems.

    ReplyDelete
  67. Its very informative blog and I am exactly looking this type of blog. Thank you for sharing this beautiful blog.

    https://superurecoat.com/titanium-iso-propoxide/

    ReplyDelete
  68. Thank you for the great information. Keep Sharing it!

    https://saroitapes.com/

    ReplyDelete
  69. Thanks for sharing informative article.

    https://web30india.com/

    ReplyDelete
  70. Excellent Article. Thank you for sharing!

    https://www.ahmedabadcomputereducation.com/
    https://www.ahmedabadcomputereducation.com/course/live-project-training-in-asp-net/
    https://www.ahmedabadcomputereducation.com/course/live-project-training-in-ios/
    https://www.ahmedabadcomputereducation.com/course/live-project-training-in-java/
    https://www.ahmedabadcomputereducation.com/course/live-project-training-in-android/
    https://www.ahmedabadcomputereducation.com/course/live-project-training-in-php/
    https://www.ahmedabadcomputereducation.com/course/live-project-training-in-python/

    ReplyDelete
  71. Excellent Article. Kepp Sharing with us!

    https://web30india.com/php-web-development-company/
    https://web30india.com/web-application-development/
    https://web30india.com/cloud-web-application-development/
    https://web30india.com/web-application-security-expertise/
    https://web30india.com/front-end-development-services-and-ux-design/
    https://web30india.com/multi-platform-integration-services/
    https://web30india.com/hire-php-programmer/

    ReplyDelete
  72. Baccarat is actually money making and it's remarkable accessibility. Optimal In your case it's readily available that you will find pretty fascinating choices. And that is thought to be one thing that is really different And it's very something that is really prepared to hit with Pretty much the most wonderful, as well, is actually a really positive option. Furthermore, it's a really fascinating solution. It is a better way which can make money. Superbly prepar The number of best-earning baccarat will be the accessibility of generting the most money. Pretty much as practical is very well suited for you A substitute that could be assured. To a wide range of accessibility and performance And find out outstanding results also.บาคาร่า
    ufa
    ufabet
    แทงบอล
    แทงบอล
    แทงบอล

    ReplyDelete
  73. Baccarat is actually money making and it's remarkable accessibility. Optimal In your case it's readily available that you will find pretty fascinating choices. And that is thought to be one thing that is really different And it's very something that is really prepared to hit with Pretty much the most wonderful, as well, is actually a really positive option. Furthermore, it's a really fascinating solution. It is a better way which can make money. Superbly prepar The number of best-earning baccarat will be the accessibility of generting the most money. Pretty much as practical is very well suited for you A substitute that could be assured. To a wide range of accessibility and performance And find out outstanding results also.บาคาร่า
    ufa
    ufabet
    แทงบอล
    แทงบอล
    แทงบอล

    ReplyDelete
  74. pgslot ซึ่งเกมคาสิโนออนไลน์เกมนี้เป็นเกมที่เรียกว่าเกม สล็อตเอ็กซ์โอ คุณรู้จักเกมส์เอ็กซ์โอหรือไม่ 90% ต้องรู้จักเกมส์เอ็กซ์โออย่างแน่นอนเพราะในตอนนี้เด็กนั้นเราทุกคนมักที่จะเอาก็ได้ขึ้นมา สล็อต เล่นเกมส์เอ็กซ์โอกับเพื่อนเพื่อนแล้วคุณรู้หรือไม่ว่าในปัจจุบันนี้เกมส์เอ็กซ์โอนั้นกลายมาเป็นเกมซะลอสออนไลน์ที่ให้บริการด้วยเว็บคาสิโนออนไลน์คุณสามารถเดิมพันเกมส์เอ็กซ์โอกับเว็บคาสิโนออนไลน์ได้โดยที่จะทำให้คุณนั้นสามารถสร้างกำไรจากการเล่นเกมส์เดิมพันออนไลน์ได้เราแนะนำเกมส์ชนิดนี้ให้คุณได้รู้จักก็เพราะว่าเชื่อว่าทุก

    ReplyDelete
  75. Nice blog, it is very much valuable information. Thanks for sharing these information with all of us. whatsapp mod

    ReplyDelete
  76. https://shulgadim.blogspot.com/2012/01/model-view-controller-mvc-pattern_13.html?showComment=1648124038771#c6985453889553580604

    ReplyDelete
  77. wordpress website design studio Need professional WordPress Web Design Services? We're experts in developing attractive mobile-friendly WordPress websites for businesses. Contact us today!

    ReplyDelete
  78. Great work! I am facing this problem, thank you for giving solution. I recommend one of the best python training institutes in Delhi that provides 200+ courses that are created by industry professionals.

    ReplyDelete
  79. People suck at DI in every language I’ve seen used in an enterprise. It’s nothing unique to C#. I could say the same thing about pretty much any issues I see with dotnet code.

    The exception is DataSets. Those only exist in dotnet, so that’s the only place people use them. I blame Microsoft, though, for including them in the Framework. They fixed it in Core, though.

    ReplyDelete
  80. I really liked the way you are delivering the content. I am just waiting for more updates from your site. Enhance your understanding and excel in Class 12 Physics with Ziyyara Edutech's comprehensive online tuition program.
    Book A Free Demo Today visit Online tutoring sites for class 12

    ReplyDelete
  81. 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:

    ReplyDelete
  82. One of the best blogs, where I collected valuable things to know. If you are a students and looking for best Chicago title format assignment then you can visit my page for complete information and also get assignment at best price.
    Visit: Chicago Title Format Assignment Help

    ReplyDelete
  83. I strongly believe that there will be great opportunities for those who looked into this area, I would like to read this blog regularly to get more important stuff...our sclinbio.com

    ReplyDelete
  84. I will have to agree don’t push it take what you can and move up to the next level in the long run you will come out to be a winner, love this video by the way and thanks
    OUR https/sclinbio.com/-

    ReplyDelete
  85. Are you on the lookout for skilled freelancers in Chennai? Look no further! At WeValueSkills, we connect businesses with talented freelancers, providing a platform that bridges the gap between demand and supply of top-notch skills.
    hire freelancers in Chennai

    ReplyDelete
  86. 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:

    ReplyDelete