Castle Windsor resolving and generics

不想你离开。 提交于 2019-12-04 22:31:43

问题


I have the following:

public interface ISubject { ... }

public class Subject<T> : ISubject { ... }

public class MyCode<T> {
    ...
    pulic void MyMethod()
    {
        var item = container.Resolve<ISubject>(); //????? how do I pass in T
    }
    ... 
 }

In this case how do i do the resolve.

Cheers Anthony


回答1:


vdhant - That's not how containers are meant to be used.

You want to use ISubject, right?. Then if you passed T you're breaking your abstraction, because your caller must know that ISubject, is actually a Subject, and more than that, its a Subject<T> and that it requires a concrete T.

No container will allow that, but it's a design problem, not tool problem.

One thing to fix your design, would be to make it explicit - change ISubject to ISubject<T>

Then you could register open generic type ISubject<> and bind it to open generic type Subject<>.

container.Register(Component.For(typeof(ISubject<>))
                            .ImplementedBy(typeof(Subject<>)));

Then you'd be able to do

var fooSubject = container.Resolve<ISubject<Foo>>();

You didn't provide any context so I may be off the track with the answer, but one thing is for sure - you have a design problem.



来源:https://stackoverflow.com/questions/872413/castle-windsor-resolving-and-generics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!