我有一个创建验证器实例的工厂。我传入一个对象进行验证,它给了我验证器,我可以用来验证它。
public class ValidatorFactory : IValidatorFactory
{
public ValidatorFactory(IComponentContext container) { _container = container; }
private readonly IComponentContext _container;
public IValidator create(object objectToValidate)
{
var validatorType = typeof(IValidator<>).MakeGenericType(new Type[] { objectToValidate.GetType() });
object validator;
_container.TryResolve(validatorType, out validator);
return validator as EntityValidatorI;
}
}
它有效,但我需要传入容器IComponentContext
。
有没有更好的方法我不需要这样做?
Autofac有"Implicit Relationship Types"但我不确定如何在这里使用它们,因为这种类型只能在运行时知道。
答案 0 :(得分:1)
IComponentContext
注入主类,而是注入泛型
Func
方法。public class ValidatorFactory : IValidatorFactory
{
public ValidatorFactory(Func<Type, IValidator> factory) { _factory = factory; }
private readonly Func<Type, IValidator> _factory;
public IValidator create(object objectToValidate)
{
var validatorType = typeof(IValidator<>).MakeGenericType(new Type[] { objectToValidate.GetType() });
return _factory(validatorType);
}
}
public static class YourBootstrapperClass{
public static void Register(ContainerBuilder containerBuilder){
containerBuilder.Register(ctx => new ValidatorFactory(type => {
object validator;
containerBuilder.TryResolve(validatorType, out validator);
return validator;
})).As<IValidatorFactory>();
}
}