我使用城堡windsor进行依赖注入并尝试注入一些通用类型。但是,当我在我的容器上调用resolve时,我收到以下错误 -
类并不满足实现类型的泛型约束。
我在此示例中暂时传递了一个简单的Car
类型。
public class CreateRequestInstance<T> where T : class, ICreateRequestInstance<T>
{
private IRequestObject<T> _IRequestObject;
public CreateRequestInstance(IRequestObject<T> requestObject)
{
this._IRequestObject = requestObject;
}
public TReturn CreateRequest<TReturn>(string provider, string type, string token, T request,
string revision, string errorCode, string errorMessage)
{
_IRequestObject.Provider = provider;
_IRequestObject.Type = type;
_IRequestObject.Token = token;
_IRequestObject.Request = request;
_IRequestObject.ErrorCode = errorCode;
_IRequestObject.ErrorMessage = errorMessage;
return (TReturn)Convert.ChangeType(_IRequestObject, typeof(IRequestObject<T>));
}
}
这是我的安装程序
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container
.Register(Component
.For(typeof(ICreateRequestInstance<>))
.ImplementedBy(typeof(CreateRequestInstance<>))
.LifestyleTransient())
.Register(Component
.For(typeof(ICreateResponseInstance<>))
.ImplementedBy(typeof(CreateResponseInstance<>))
.LifestyleTransient())
.Register(Component
.For(typeof(IRequestObject<>))
.ImplementedBy(typeof(RequestObject<>))
.LifestyleTransient())
.Register(Component
.For(typeof(IResponseObject<>))
.ImplementedBy(typeof(ResponseObject<>))
.LifestyleTransient());
}
这是我的班级工厂电话
public T GetConcreteClass<T>()
{
var someClass = container.Resolve<T>();
return someClass;
}
这是调用代码
var t = factory.GetConcreteClass<ICreateRequestInstance<ICar>>();
var test = t.CreateRequest<ICar>("provide", "test", "test", car, "1", "this is a test", "fred");
对此有任何帮助将不胜感激
答案 0 :(得分:4)
public class CreateRequestInstance<T> where T : class, ICreateRequestInstance<T>
看起来并不正确。您正在声明一个需要模板参数的类,该模板参数是实现ICreateRequestInstance<T>
的类。有了这个,除非你的Car
类型实现ICreateRequestInstance<T>
(我怀疑它),否则你会收到错误。
我认为你真的打算:
public class CreateRequestInstance<T> : ICreateRequestInstance<T> where T : class
这是一个实现ICreateRequestInstance<T>
的类,它需要一个任何类的模板参数。