开发者

Injecting an Open Generic Interface with a non Generic implementation using Castle

开发者 https://www.devze.com 2023-03-09 21:51 出处:网络
I have an open generic interface, which i implement with a non generic class, and i want to inject this class using castle windsor, but am struggling.....

I have an open generic interface, which i implement with a non generic class, and i want to inject this class using castle windsor, but am struggling.....

Lets say i have the following interface

public interface IMyInterface<T>
{
    bool DoSomething(T param);
}

And then i have the following class that implements this interface like so

public class MyClass : IMyInterface<string>
{
    public bool DoSomething(string param)
    {
        // Do Something
        return true;
    }
}

I want to be able to resolve the interface using castle like this, so that the injectedObject becomes an instance of MyClass.

WindsorContainer container = new WindsorContainer(new XmlInterpreter(newConfigResource("castle")));
IMyInterface<string> injectedObject = container.Resolve<IMyInterface<string>>();

Is this possible, or have i gone off track slightly? If its possible, how do i set up the castle config section? I have tried开发者_StackOverflow社区 using the '1 notation to indicate that the interface is an open generic type, but you get an error if the implementation is not also generic, which in this case it is not.

Any help appreciated


We use the fluent interface in my team so it's been a while since I've looked at the config file syntax. The basic principle is this: your service is IMyInterface<string> and the implementing type is MyClass. So I think it would be something like this:

<component service="Namespace.IMyInterface`1[[System.String, mscorlib]], AssemblyName"
        type="Namespace.MyClass, AssemblyName" />

You say you get an error. What is the error? I guess it is because you have defined the service as IMyInterface<> without supplying the type parameter. If you want to do that, as your question implies, the implementing type must also be generic:

<component service="Namespace.IMyInterface`1, AssemblyName"
        type="Namespace.MyGenericClass`1, AssemblyName" />

Note that you can register both components. If you do that, resolving IMyInterface<string> will get you an instance of MyClass, while resolving IMyInterface<AnyOtherType> will get you an instance of MyGenericClass<AnyOtherType>.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号