如果我已经正确理解你的问题,我认为实现你想要的东西的唯一方法是通过某种可怜的人的依赖注入(有争议的 - 请不要投票给我!)因为Winforms设计师生成一种构建您所说的各种子控件的方法,这对IoC来说显然是不可靠的。
我不知道你将能够做财产注入,但你可以利用的构造,这里是一个头发右脑方案我刚刚炮制...
首先,创建一些方式来访问你的温莎容器 - 这样的事情可能会做的伎俩:
public static class MyContainer
{
private static readonly IWindsorContainer _container = Bootstrap();
// I did it like this so that there is no explicit dependency
// on Windsor - this would be the only place you need to change
// if you want an alternate container (how much you care about
// that is up to you)
public static T Resolve<T>()
{
return _container.Resolve<T>();
}
private static IWindsorContainer Bootstrap()
{
var container = new WindsorContainer();
container.Install(FromAssembly.This());
// ... whatever else you need to do here
return container;
}
}
其次,在内部控制,要将一些属性注入做这样的事情(我去了好醇” ILogger作为东西的例子中,你可能想要注射):
public partial class MyFancyControl : UserControl
{
// Constructor to keep the winforms designer happy
public MyFancyControl()
: this (MyContainer.Resolve<ILogger>())
{
// Intentionally always blank as this
// is an un-unit-testable method
}
// Constructor that does the actual work
public MyFancyControl(ILogger logger)
{
InitializeComponent();
Logger = logger;
}
public ILogger Logger { get; private set; }
}
注意:使用记录器会引发一对明显的气味 - 有时候您根本没有在容器中注册这样一个组件(通常您有一个空记录器),因此您可能需要连接某种形式的机制,但如果你需要或不需要,我会留给你。
来源
2012-07-04 13:30:05
kmp
它很安静,我可以听到蟋蟀。这必须是其他人不想做的事情,没有人应该尝试去做,或者做不到的事情。 –
如果你想Windsor管理嵌套控件的依赖关系,为什么不让Windsor管理它们,包括创建它们? – kko
我正在讨论作为InitializeComponent方法的一部分创建的嵌套控件,其中构造了由设计器创建的所有控件。我仍然希望能够使用WinForms设计器来构建我的用户控件。正是这些控件我希望能够注入依赖。实际上,将这些属性视为属于外部用户控件。 –