简体   繁体   中英

Is it possible to make Autofac fail if there are multiple singleinstance-registrations for a single interface?

When multiple single-instances are registered for a single interface, it seems that Autofac's default behavior is to let them overwrite each other, such that latest registration is the one that'll be used to build the container. Is there anyway to change this behavior, such that the application will simply fail to run if this happens?

I've tried looking through the documentation, and found stuff like.IfNotRegistered(), but that will simply reverse the effect, st the first registration will be the valid one. What I'd like is a way to simply prevent the application from ever running, if there are multiple singleinstance registrations under the same interface.

Unfortunately, there is not an out of the box way to do what you're trying to do. The majority use case is that the override behavior is desired.

One additional effect of registering multiple implementations of a given service is that if you resolve IEnumerable<T> of that service you'll get all the registered implementations. You couldn't do that if registering multiple was blocked.

You could use that to your advantage - after container build, resolve the IEnumerable<T> of your service and throw an exception if there is more than one.

However, there isn't something on Autofac itself that you can toggle to enable that behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM