Closed Ergamon closed 8 months ago
You can can call Container.GetTypesToRegister
to find the types that Collection.Register
would otherwise register:
// Get all handler types
var handlers =
container.GetTypesToRegister(
typeof(IMessageHandler<>), Assembly.GetExecutingAssembly());
// Register them
container.Collection.Register(typeof(IMessageHandler<>), handlers);
// Extract the messages from them
var messages = (
from implementation in handlers
let service = implementation.GetClosedTypeOf(typeof(IMessageHandler<>))
let messageType = service.GetGenericArguments().First()
select messageType)
.Distinct()
.ToArray();
This allows you to retrieve the handlers and messages in an early stage of the registration process.
The other option is to query the container after the last registration has been made:
var messages = (
from registration in container.GetCurrentRegistrations()
let serviceType = registration.ServiceType
where serviceType.IsClosedTypeOf(typeof(IMessageHandler<>))
let handlerType = serviceType.GetClosedTypeOf(typeof(IMessageHandler<>))
let messageType = handlerType.GetGenericArguments().First()
select messageType)
.Distinct()
.ToArray();
This requires that all registrations have been made and Container.Verify()
has been called.
When I register all my instances of an open generic type like this:
how do I get all possible T values?
Why do I want this: I have an application listening to RabbitMQ messages. The library I am using has a method for this with a signature:
So my idea was to have an interface like this:
Actual implementations look like this:
At startup I have a hosted service getting the necessary dependencies:
I know it is a lot of ugly reflection code and the service has a dependency to the container. But I think the design is ok, cause I consider this hosted service more or less as part of my composition root.
So basically my question is, how to implement this
GetRegisteredTypes
method or is there a better design to achieve what I want?