In the previous blog post we added some unit tests that tested the WebAPI and also included the RavenDB storage behind it. As I explained the recommendation is not to use fakes or mocks but just to use the in memory variant of RavenDB during testing. However the WebAPI controller used a static RavenConfig.Store property to get to the RavenDB database. And that is the kind of hard coupling we would prefer not to have even if we don’t need to create a fake for our tests.
Adding Ninject to do our server side dependency injections
There are many dependency frameworks you can use with your .NET code. I am not going to comment on their respective quality and merits, I have used several and most work just fine. That said I have always liked Ninject so that is what I am going to use here.
In this case we are just worried about the WebAPI and even though Ninject doesn’t have that in the box there is a pretty good blog post by Peter Provost describing how to set things up. So basically adding his code will take care or the enabling Ninject with WebAPI.
Registering RavenDB with Ninject
That still leaves us with registering RavenDB with Ninject. There are different ways of doing this and this answer by Ronnie Overby on StackOverflow show a great way of doing so. We will expand on this in the future but for now that will work just fine.
Updating the MoviesController
With the dependency injection in place we can change the update the movies controller to receive its dependency on the RavenDB session in its constructor as shown below.
1: public class MoviesController : ApiController
3: private readonly IDocumentSession _session;
5: public MoviesController(IDocumentSession session)
7: _session = session;
10: public IEnumerable<Movie> GetMovies()
12: return _session.Query<Movie>().ToList();
15: public void PostMovie(Movie movie)
Updating the unit tests
Changing the MoviesController means we have to update our unit tests. The most important part is the test setup where we now inject the RavenDB session into the MoviesController.
2: public void TestInitialize()
4: // Arrange
5: _documentStore = new EmbeddableDocumentStore
7: ConnectionStringName = "RavenDB"
10: _session = _documentStore.OpenSession();
11: _controller = new MoviesController(_session);
Adding dependency injection on the server might not seem like a big deal yet but it will make the application much more manageable on the long run so I consider it a must have.
Index of posts on the RAW stack
See here for more posts on the RAW stack.