I am trying to figure out how to resolve a type by name from the container at runtime using Autofac 3.5.2. My use case is that each business partner has a custom callback strategy that require injection of different types by the container, but I don't know which partner strategy I need until runtime. So:
class PartnerAStrategy(ISomeType aSomeType, ILog someLog) : ICallbackStrategy {}
and
class PartnerBStrategy(ISomeOtherType aSomethingElse, IShoe aSneaker) : ICallbackStrategy {}
I know which strategy I need after the class that will use it has already been resolved
class PartnerSSOController {
void PartnerSSOController(IPartnerFactory aFactory){
thePartnerFactory = aFactory;
}
void DoLogin(){
// 'PartnerB'
string aPartner = GetPartnerNameFromContext();
//get from container, not reflection
ICallbackStratgey aStrategy = thePartnerFactory.ResolveCallback(aPartner);
aStratgey.Execute();
}
}
class PartnerFactory : IPartnerFactory{
ICallbackStratgey ResolveCallback(string aPartnerName){
string aCallbackTypeINeed = string.format("SSO.Strategies.{0}Strategy", aPartnerName);
// need container to resolve here
}
}
Assuming that everything has been successfully registered with the container, how would I register the callback in my Autofac SSO module? I've tried this:
aBuilder.Register(aComponentContext => {
IPartnerFactory aFactory = aComponentContext.Resolve<IPartnerFactory>();
string aTypeName = String.Format("SSO.Strategies.{0}Strategy", /** how to access partner name here? **/);
Type aTypeToReturn = Type.GetType(aTypeName, false, true) ?? typeof(DefaultCallbackStrategy);
return aComponentContext.Resolve(aTypeToReturn);
})
.As<ICallbackStrategy>()
but as you can see, I can't figure out how to make the partner or type name available during callback. I would prefer to avoid registering each partner's callback specifically and providing a key name, if possible, as I like to scan the assembly for the types in my module:
aBuilder.RegisterAssemblyTypes(typeof(CallbackBase).Assembly)
.Where(aType => typeof(ICallbackStrategy).IsAssignableFrom(aType))
.AsImplementedInterfaces()
.AsSelf();