I’m just starting out with IoC frameworks and have been playing with Autofac.
In the following example code where I am registering 2 completely different classes (in global.asax) that both implement the same interface, I am wondering how we ensure the correct one is used by Autofac? At present, one of my controller’s that takes an IPhotoBlogRepository as its constructor, is passed either a PhotoBlogRepository OR a TestRepository, depending on which appears first/last in the below code.
builder.RegisterType<PhotoBlogRepository>().As<IPhotoBlogRepository>();
builder.RegisterType<TestRepository>().As<IPhotoBlogRepository>();
This is by design. A container cannot out of the box know which service you intended. If in production code there will only be one implementation of the interface, then your registration code should make sure that no more than one service is registered.
If you intend to support multiple implementations, then your controller could take a dependency on
IEnumerable<IPhotoBlogRepository>. Autofac will give the controller a collection of all registered services implementing that interface.If the controller need even more fine-grained control, take a look at how Autofac supports metadata.
That said: from your sample I see that you are registering a test implementation of the interface. In unit tests I seldom resolve the SUT (your controller in this case) from a container, but rather instantiate it directly. This eliminates the problem of “replacing” real services with fake ones since you will always hand them directly to the controller constructor.