[英]How to register generic class with AutoFac that requires parameters?
AutoFac 允许您使用builder.RegisterGeneric(Type type)
注册泛型类,但它不接受构造参数。 该方法的描述甚至说:
注册一个未参数化的基因类型
但是,如果我有一个由Service实现的通用接口IService,它需要一些参数呢?
目前我已经这样注册了:
builder.Register(c =>
new Service<Class1>(
parameter1,
parameter2))
.As<IService<Class1>>();
在注册时,我必须指定 T 的确切类型(在本例中为 Class1)。 我可以更一般地做这件事,以便我有一个适用于任何 T 的注册吗?
这里记录了每一件事: https : //autofaccn.readthedocs.io/en/latest/register/parameters.html
基本上,您可以继续使用RegisterGeneric
并使用WithParameter
builder.RegisterGeneric(typeof(Service<>))
.WithParameter("nameOfParam1", parameter1)
.WithParameter("nameOfParam2", parameter2)
.As(typeof(IService<>));
对于那些寻找多种 Ttypes 的人(像我一样)。
builder.RegisterGeneric(typeof(BaseGeneralCrud<,,>)).As(typeof(IBaseGeneralCrud<,,>)).InstancePerLifetimeScope();
这是类定义的样子:
public class BaseGeneralCrud<TEntity, TDto, TIdType> : IBaseGeneralCrud<TEntity,TDto,TIdType>
where TEntity : class, IHasIdColumn<TIdType>
where TDto : IHasIdColumn<TIdType> , new()
where TIdType : notnull
{
private readonly IRepository<TEntity,TIdType> _repository;
private readonly IMapper _mapper;
public BaseGeneralCrud(IRepository<TEntity,TIdType> repository, IMapper mapper)
{
_repository = repository;
_mapper = mapper;
}
// there are some methods defined here..
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.