4
votes

I am using castle windsor for dependency injection and trying to inject some generic types. However when I call resolve on my container I get the following error:

Class doesn't satisfy generic constraints of implementation type.

I'm passing a simple Car type at the moment in this example.

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>));
    }  
}

This is my installer:

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());
}

This is my class factory call:

public T GetConcreteClass<T>()
{
    var someClass = container.Resolve<T>();
    return someClass;
}

and this is the calling code:

var t = factory.GetConcreteClass<ICreateRequestInstance<ICar>>();

var test = t.CreateRequest<ICar>("provide", "test", "test", car, "1", "this is a test", "fred");

Any help with this would be appreciated.

1

1 Answers

5
votes
public class CreateRequestInstance<T> where T : class, ICreateRequestInstance<T>

That doesn't look right. You're declaring a class that expects a template parameter that is a class that implements ICreateRequestInstance<T>. With this, you would get the error you're seeing unless your Car type implements ICreateRequestInstance<T> (which I doubt it does).

I think you really intended:

public class CreateRequestInstance<T> : ICreateRequestInstance<T> where T : class

This is a class that implements ICreateRequestInstance<T> that expects a template parameter that is any class.