Programmaticaly configuring container before usage

Aug 13, 2009 at 9:24 AM


I have a class (lets call this MyServer) that is using a container to instantiate another class. For instance the MailProvider class that implements the IMailProvider. To do this I configure container using RegisterType in the constructor of MyServer and later I call ResolveType.

When MyServer is instantiated from a unit test I want to instantiate another IMailProvider (MockMailProvider) instead of the real one, but using code instead of configuration file.

How do you suggest I do that? I was thinking to pass to the constructor of MyServer a Container instantiated and configured in my unit test. But I have additional interfaces registered to my container which I want to be the same both on production and unit tests.


Dec 18, 2009 at 1:26 AM

Is the only reason MyServer has a container is because it wants to create an IMailProvider? Is there a reason it can't just get the IMailProvider directly?

Another option would be to inject a MailProviderFactory instead.

Failing that, pass in the container from the outside. Reconfiguring the container with the same types is not an error, and it's last one in wins. That means you could set up your container from the config file from production, for instance, and then reconfigure the test specific stuff. That's not really a unit test at that point though.