【发布时间】:2016-04-16 14:24:14
【问题描述】:
我是 Autofac 的新手,在解析嵌套的开放式通用服务类型时遇到了一些麻烦。
我希望我的ContactService 实现两个接口。两个接口都使用相同的泛型类型参数,但第二个是嵌套的:
class ContactService<TParent>
: IContactService<TParent>,
IFeatureProvider<ContactFeature<TParent>>
where TParent : class, IDomainModel
{ }
如果我这样做:
builder
.RegisterGeneric(typeof(ContactService<>))
.As(typeof(IContactService<>))
.As(typeof(IFeatureProvider<>);
然后尝试解析服务IFeatureProvider<ContactFeature<Household>>(例如)导致Autofac尝试实例化
ContactService<ContactFeature<Household>>
而不是
ContactService<Household>
我明白为什么上述方法不起作用。所以我尝试了这个:
builder
.RegisterGeneric(typeof(ContactService<>))
.As(typeof(IContactService<>))
.As(typeof(IFeatureProvider<>)
.MakeGenericType(typeof(ContactFeature<>)));
但是,我仍然收到类似的错误:
TypeLoadException: GenericArguments[0], 'ContactFeature`1[Household]',
on 'Contact`1[TParent]' violates the constraint of type parameter 'TParent'.
System.RuntimeTypeHandle.Instantiate(RuntimeTypeHandle handle, IntPtr* pInst,
Int32 numGenericArgs, ObjectHandleOnStack type)
ArgumentException: GenericArguments[0], 'ContactFeature`1[Household]',
on 'IContactService`1[TParent]' violates the constraint of type 'TParent'.
System.RuntimeType.ValidateGenericArguments(MemberInfo definition,
RuntimeType[] genericArguments, Exception e)
看起来 Autofac 试图将 ContactFeature<Household> 传递为 TParent 而不仅仅是 Household。
抱歉,解释太长了。我希望有人能帮我解决这个问题!
谢谢。
【问题讨论】: