I’m going to use structuremap for a project I’m working on. The basic gist is that I have a repository pattern with an NHibernate implementation, but I want to use StructureMap to load the repositories in case I ever decide to switch to a Linq2Sql or other type of implementation. I know how to initialize structuremap, but my question is where? Should the web application that uses my library be responsible for configuring the registry? Should I have a default implementation in my library? Where would it fit best?
My library structure at the moment looks like:
- Library.Data
- Library.Data.NHibernate
- Library.Domain
The .Domain namespace contains the actual entities, while the .Data namespace contains the interfaces for the repository. The .Data.NHibernate namespace contains the NHibernate implementation of those interfaces.
When using IoC containers, the calling application should ideally be responsible for configuring all dependencies.
A well-structured system will demand dependent objects as constructor parameters. How you invoke those constructors is independent of StructureMap or any other technique, but can only be specified at the point at which the “top most” object is used. Separation in this way will allow applications to inject dependencies in whichever way they desire and gives you that warm fuzzy feeling you can only get from having great separation of concerns.
I’m not entirely sure what you mean by a “default” implementation in the context of your library. Your “default” implementation (configured by your StructureMap registry) will be the instance you get back when you ask StructureMap for an implementation of a given interface (presumably some kind of
IRepositoryin your case), without specifying any other criteria.For you, you will want this instance to be configured as your NHibernate implementation. Presumably this implementation already lives in the
Library.Data.NHibernatenamespace as your “NHibernate Repository”. You shouldn’t need to create any other implementation unless you want to change yourIRepositoryimplementation to something else.