开发者

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 c开发者_如何学运维ompletely 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.


As pointed out above, metadata is probably the way you want to go with this, but if you just want to simply ensure that the first implementation is chosen then you should use PreserveExistingDefaults() for all the additional registrations i.e.:

builder.RegisterType<PhotoBlogRepository>().As<IPhotoBlogRepository>();
builder.RegisterType<TestRepository>().As<IPhotoBlogRepository>().PreserveExistingDefaults();

The last registration is the one which will be chosen as the default without applying PreserveExistingDefaults().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜