温莎城堡解决和泛型 [英] Castle Windsor resolving and generics

查看:122
本文介绍了温莎城堡解决和泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好 我有以下几点:

Hi guys 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.

干杯 安东尼

推荐答案

vdhant - 这不是如何集装箱意味着要使用

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

您想要使用 ISubject ,对不对?然后,如果你完成了T你打破你的抽象,因为你的调用者必须知道, ISubject ,其实是一个主题,而更重要的是,它的一个受试对象; T&GT; ,它需要一个混凝土T

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.

一件事来解决你的设计,将使其明确 ​​- 变化 ISubject ISubject&LT; T&GT;

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

然后,你可以注册开放式泛型类型 ISubject&LT;&GT; 并将其绑定到开放式泛型类型受试对象;&GT;

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.

这篇关于温莎城堡解决和泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆