【发布时间】:2014-03-05 09:32:45
【问题描述】:
遇到知识鸿沟,离开 WinForms 这么久了,不确定我是否为温莎城堡正确地做这件事。
在过去的 5 年里,我一直在开发 ASP.Net 应用程序(WebForms、MVC 等)。我现在有一个项目,其中 Web 界面还不是一个可行的解决方案。所以我们用 WinForms 来做。
使用 Asp.Net,我只需设置 Castle Windsor Container、CWC、静态类,一切都将自行处理依赖注入等。
我在使用 WinForms 时遇到了一些问题。我显然无法实现与 WebForms 开发相同的依赖注入规则。
当前实施:
程序.cs:
static void Main () {
Initialize();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
var form = CWC.Resolve<frmMain>();
Application.Run( form );
}
public static void Initialize ( string log4netPath = null ) {
var container = new WindsorContainer();
container.Kernel.ComponentModelCreated += ( s => {
if ( s.LifestyleType == LifestyleType.Undefined )
s.LifestyleType = LifestyleType.PerWebRequest;
} );
container.Install(
new CoreManagerInstaller() ,
new DomainInstaller() ,
new RepositoryInstaller() ,
new ServiceInstaller()
);
//Installer for MVC framework -- Must be done after other installers on its own.
container.Install( new AppInstaller() );
if ( log4netPath != null ) {
//container.AddFacility( new LoggingFacility( LoggerImplementation.Log4net , log4netPath ) );
}
CWC.Init( container );
}
AppInstaller:
public class AppInstaller : IWindsorInstaller {
#region IWindsorInstaller Members
public void Install ( IWindsorContainer container , IConfigurationStore store ) {
container.Register(
Classes.FromThisAssembly()
.BasedOn<CIMForm>().LifestyleTransient() ,
Classes.FromThisAssembly()
.BasedOn<CIMTabControl>().LifestyleTransient() ,
Classes.FromThisAssembly()
.BasedOn<CIMTabPage>().LifestyleTransient() ,
Classes.FromThisAssembly()
.BasedOn<UserControl>().LifestyleTransient() );
}
#endregion
}
以上所有内容都不是新的或有问题的atm。
问题子项是我试图从其他库中引用接口的 UserControl。在 WebForms 中,我会删除属性签名并开始在我需要的事件/方法中使用它。
这样:
public partial class ClientInformationControl : UserControl {
public IServerRepository ServerRepository { get; set; }
private void ClientInformation_Load ( object sender , EventArgs e ) {
var servers = ServerRepository.Find().Select( s => new { Key=s.Id , Value=s.Name } );
cboServers.Items.AddRange( servers.ToArray() );
}
}
但是ServerRepository 在这个设计中永远不会被实例化。我必须手动致电CWC.Resolve<IServerRepository>(),以便该物业获得所需的信息。
有没有办法让 ServerRepository 自动(神奇地)填充来自容器的对象数据?
尝试执行public ClientInformationControl(IServerRepository serverRepo){},但赋值并没有持续通过构造函数,因此当触发 Control.Load 事件时,ServerRepository 属性已被清空。
【问题讨论】:
-
I now have a project where a web interface is not a viable solution, yet. So we are doing it with WinForms.- 只是一个旁注。不建议将 winforms 用于任何新项目。它是一种非常古老的技术,已被更现代、可扩展、可定制、更快、独立于分辨率、基于矢量、硬件加速、美观、基于 XAML 的技术所取代(这些技术也更接近于 Web 范式而不是winforms,并启用更清晰的模式)。你真的应该重新考虑你的决定。我无意用此评论冒犯任何人。 -
感谢您的非建设性评论。在各种框架中这样做是有原因的,而这恰好是他们的基础架构需要并且可以处理的原因。
标签: winforms dependency-injection castle-windsor