Last weekend I have attended another SharePoint Saturday, this time in Stockholm. The weather was nicer than the last year, and the attendance was over the top: 300 attendees to learn about and discuss SharePoint topics from the expert speakers.
My talk was about how to build SharePoint code that’s both maintainable and testing-friendly. I have approached the talk from the coarse to finer detail, from the distribution of the solution components into SharePoint to the dependency injection mechanisms and principles of SOLID and GRASP object-oriented design.
The demo I shared with the attendees was a very simple SharePoint provider-hosted app in ASP.NET MVC that displays the user full name and the login username. I started with a very coupled code that all sat in the Index action in the controller and I ended with a testable design that had the SharePoint ClientContext dynamically injected to the service at runtime, dutifully abstracted behind an interface. I used Unity IoC container and Moq for mocking the dependencies in the tests.
You can find the slides at my SlideShare page, as usual, and the source code for the demo (in a form of a Mercurial repository) on my OneDrive. I have received some very good comments about the topic and the techniques mentioned in the session.
If you have attended my session at SPS Stockholm, I have questions for you.
- What have you liked most?
- What haven’t you liked at all?
- What could be done better?
Let me know how can I improve the talk for future events.
Hi Edin,
Thanks by your post, I find it really interesting.
What I’d like to know if about using Unity IoC or another dependicies injector in SharePoint farm solutions. How can I do it?. I had been thinking about using a own simple dependencies injector which uses webconfig to define the mapping. But I think that it would be better if I use Unity and I don´t know how to do it. When I work with MVC, I have a specific place where I can configure and map dependencies but I don´t know in SharePoint.
Thanks again by your information.
Regards
Hello!
As you have said, in SharePoint full trust code solutions there’s no explicit way of injecting dependencies. You can build your own (if you want) but one approach that has been used by Microsoft PnP team some years ago was to extend SPHttpApplication class and change the SharePoint web application Global.asax file to use it. You can find more information here: https://webclientguidance.codeplex.com/wikipage?title=How%20To%3a%20Enable%20Unity%20in%20a%20SharePoint%20Application%20to%20make%20Web%20Parts%20more%20testable
Hello Edin,
Thank you for the information about unit testing Provider hosted app. I am looking for a demo code to inject the client context into the controller dynamically, the link provided in the blog is not working. Could you please share the correct/updated one drive link for the demo code, that will greatly help me.
Thanks again!!
Regards..
I’ve updated the link 🙂 Thanks for letting me know!