简体   繁体   中英

Registration of ephemeral components in Autofac

I am using Autofac in an application that reads and writes information from a number of "devices". These devices can come and go at any point and their lifetime is outside of the control of the application. They can also be found on different interfaces; USB and IP networks. All devices have a common IDevice interface.

What would the suggested mechanism be for integrating the discovery of this within Autofac? Since the devices themselves are ephemeral I know that I would need to be able to remove them from the container, I also found in a SO search that this isn't possible ( Is it possible to remove an existing registration from Autofac container builder? )

I am now leaning more to the idea of having a factory registered within Autofac ( IDeviceFactory or similar) and then querying that factory for the current device list when needed. That factory would maintain it's own internal list of available hardware interfaces (USB COM ports or ethernet interfaces) and then the list of devices available on those hardware interfaces.

It just feels like I am potentially losing out on a lot of the benefits of Autofac if I don't use it for the IDevice itself. Should I be investigating modifying the service resolver pipeline?

I don't want to fall in to the trap of desperately trying to "Autofac all the things," if it isn't the right tool. but I also don't want to unnecessarily write my own component registry that lives alongside Autofac.

Autofac isn't going to be the way here, go with the factory.

For performance reasons, Autofac needs to be able to cache registrations, one of the many reasons you can't remove things from the container. Hypothetically you could create a lifetime scope with the devices in it and dispose/recreate that every time the device list changes, but that's going to make your app unstable since anything resolved from that scope will also be disposed and recreated.

It's also possible, it sounds like, that the device list may change as some class logic is executing. You'll want the latest list at the time you need to work with the devices, which means querying at that point - just like you'd query data from a database as you need it rather than inject it as a dependency.

Just go with the factory.

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