Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IoC using Autofac

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>();
like image 344
marcusstarnes Avatar asked Jul 09 '26 06:07

marcusstarnes


1 Answers

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.

like image 149
Peter Lillevold Avatar answered Jul 11 '26 19:07

Peter Lillevold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!