Friday, 10 August 2012

SharePoint and IoC container

I was given a task to write a timer job that needs to read data from SharePoint list. My colleague has written a timer job for that purpose but the code was reading data directly from the database. So when I tried to use but could not because it was tight couple.

So I decided to modify that code in a plug-able way so that I can choose various data sources to be used with the same timer job for different clients. I implemented OCP (Open Closed Principal).

I have used StructureMap as IoC container to inject my dependency to SharePoint timer job. Because it is easy to use and other reason was it allows us to configure dependencies in a separate configuration file so I don't need to touch OWSTIMER.config file.

I wrote an interface called IRepository, and configured my timer job to pick the implementation from IoC container.
The container was configured with the concrete implementation class. If I want my timer job to read data from csv file, I just need to change the settings/configuration in IoC config.

Below is my project structure:

You can see there is a project called "Masood.SharePoint.ProcessingTimerJob.Interfaces" and it has got IRepository interface.

And Masood.SharePoint.ProcessingTimerJob.Repositories has got actual implementation of IRepository class.

So I can distribute Masood.SharePoint.ProcessingTimerJob.wsp to anyone who wants to use it, they  just need to implement that interface and timer job is read to process from your data source. You can download full source code from Codeplex.

Below is structure map config file that is use to inject actual implementation

Some output

That's it.