I have something like the following class:
public class MessagePublisher : IMessagePublisher
{
private readonly IComponentContext componentContext;
public MessagePublisher(IComponentContext componentContext)
{
this.componentContext = componentContext;
}
public void PublishMessage<T>(T message) where T : class
{
var messageConsumers = componentContext.Resolve<IEnumerable<IMessageConsumer<T>>>();
foreach (IMessageConsumer<T> messageConsumer in messageConsumers)
{
// Do some stuff.
}
}
}
}
This... doesn't work. I get an error from Autofac indicating I can't store the component context like I have, which makes sense.
This resolve operation has already ended. When registering components using lambdas, the IComponentContext 'c' parameter to the lambda cannot be stored. Instead, either resolve IComponentContext again from 'c', or resolve a Func<> based factory to create subsequent components from.
I totally get why this doesn't work. What I'm wondering is if there's an alternate way to do what I'm trying to do, which is to resolve a type within a method (I can't pass it in via the constructor, since I don't know the type at that point). Any ideas? Thanks for your help.