我有一个泛型类 ( GenericClass
),它依赖于泛型类型 ( IGenericDependency
)。这种依赖也是通用的。
public class GenericClass<T>
{
private readonly IGenericDependency;
}
类型参数直到运行时才知道。
到目前为止,我已经这样做了:
我正在注入一个 Func。
public class GenericClass<T> : IGenericClass<T> where T:class , new()
{
private readonly IGenericDependency _genericDependency;
public GenericClass(Func<TypeIGenericDependency>> factory)
{
_genericDependency = factory(T);
}
}
以及重新注册代码:
builder.RegisterGeneric(typeof (GenericClass<>)).As(typeof (IGenericClass<>));
builder.Register<Func<Type, IGetDataCollection>>(c =>
{
var context = c.Resolve<IComponentContext>();
return type =>
{
if(type.Name.EndsWith("Entity"))
{
return (IGenericDependency)
context.Resolve(typeof (GetEntityCollection<>)
.MakeGenericType(type));
}
if(type.Name.EndsWith("TypedList"))
{
return (IGenericDependency)
context.Resolve(typeof (GetTypedList<>)
.MakeGenericType(type));
}
throw new NotSupportedException("Not supported type");
};
});
我想知道是否有另一种方法可以做到这一点。