我使用城堡温莎进行依赖注入,并尝试注入一些通用类型.但是,当我在容器上调用resolve时,出现以下错误-
Class doesn’t satisfy generic constraints of implementation type.
在此示例中,我现在传递的是简单的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");
任何帮助,将不胜感激
解决方法:
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>的类.期望模板参数是任何类.