【发布时间】:2014-10-20 23:29:48
【问题描述】:
我试图弄清楚如何使用 Autofac 3.5.2 在运行时从容器中按名称解析类型。我的用例是每个业务伙伴都有一个自定义回调策略,需要容器注入不同的类型,但是直到运行时我才知道我需要哪种伙伴策略。所以:
class PartnerAStrategy(ISomeType aSomeType, ILog someLog) : ICallbackStrategy {}
和
class PartnerBStrategy(ISomeOtherType aSomethingElse, IShoe aSneaker) : ICallbackStrategy {}
我知道在使用它的类已经解决之后我需要哪种策略
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
}
}
假设一切都已成功注册到容器中,我将如何在我的 Autofac SSO 模块中注册回调?我试过这个:
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>()
但如您所见,我不知道如何在回调期间使合作伙伴或类型名称可用。 我宁愿避免专门注册每个合作伙伴的回调并尽可能提供键名,因为我喜欢扫描程序集以查找我模块中的类型:
aBuilder.RegisterAssemblyTypes(typeof(CallbackBase).Assembly)
.Where(aType => typeof(ICallbackStrategy).IsAssignableFrom(aType))
.AsImplementedInterfaces()
.AsSelf();
【问题讨论】:
标签: dependency-injection autofac