下面的类在其构造函数中接收工厂委托,该委托在给定T
的情况下返回EndPointType
。我的问题是如何在AutoFac注册这个工厂?如果我的方法有误,我如何完成使用工厂解决类型的任务?
Func<EndPointType,T> serviceFactory // how do I register this?
public class AutoFacClientResolver<T>
{
private Func<Type, IAPI> apiFactory;
private Func<EndPointType, T> serviceFactory;
private Func<EndPointType, IEndPointValidator> validatorFactory;
public IEndPointConfiguration CurrentEndPoint;
public AutoFacClientResolver(
Func<Type, IAPI> apiFactory,
Func<EndPointType, T> serviceFactory,
Func<EndPointType, IEndPointValidator> validatorFactory
)
{
this.apiFactory = apiFactory;
this.serviceFactory = serviceFactory;
this.validatorFactory = validatorFactory;
}
public virtual T ResolveClient()
{
T client = default(T);
var typeofT = typeof(T);
IAPI api = apiFactory(typeofT);
foreach (IEndPointConfiguration endPoint in api.EndPoints)
{
CurrentEndPoint = endPoint;
client = serviceFactory(endPoint.EndPointType);
IEndPointValidator validator = validatorFactory(endPoint.EndPointType);
if (!validator.IsInterfaceAlive(endPoint))
continue;
break;
}
return client;
}
}
其他注册工厂/对象:
builder.Register<Func<EndPointType, Type>>(
c => ep => c.ResolveKeyed<Type>(ep));
builder.Register<Func<EndPointType, IEndPointValidator>>(
c => ep => c.ResolveKeyed<IEndPointValidator>(ep));
builder.RegisterGeneric(typeof(AutoFacClientResolver<>));