使用Unity进行桌面应用程序依赖注入

时间:2015-03-29 22:17:50

标签: c# winforms dependency-injection unity-container

我使用了与MVC Web App的统一性。 在MVC中我们有app_start方法。 我们用

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

这将参数发送到Controller Constructor。 现在我想找到如何将这种模式实现到DesktopApplication。

你们知道我们使用新的Form1()。Show(); // bla bla foo 当我创建一个新表单时,我可以创建一个System.Windows.Forms类型的新实例,它会自动将参数发送给构造函数。

对不起我的语言。 现在我正在使用这样的东西,并询问它是否是一个更好的解决方案:

public partial class frm_FirmaSecimi : XtraForm
{
    private IFirmaService _firmaService;

    public frm_FirmaSecimi()
    {
        InitializeComponent();
        _firmaService = UnityConfig.Container.Resolve<IFirmaService>();
    }
}

有没有办法把它变成:

public partial class frm_FirmaSecimi : XtraForm
{
    private IFirmaService _firmaService;

    public frm_FirmaSecimi(IFirmaService firmaService)
    {
        InitializeComponent();
        _firmaService = firmaService;
    }
}
顺便说一句,这是一个DevExpress表格。 谢谢你的答案。

1 个答案:

答案 0 :(得分:1)

尝试为表单引入接口,然后在每个表单上使用它:

public class FormMain : IFormMain
{
    ISubForm _subForm;

    public FormMain(ISubForm subForm) 
    {
        InitializeComponent();
        _subForm = subForm;
    }

    ...

}

现在,在程序启动时,创建Unity容器,并解析IFormMain依赖项:

private static void Main()
{
    var container = BuildContainer();
    Application.Run(container.Resolve<IFormMain>());
}

public static IUnityContainer BuildContainer()
{
    var currentContainer = new UnityContainer() ;
    currentContainer.RegisterType<IFormMain, FormMain>();
    // note: registering types could be moved off to app config if you want as well
    return currentContainer;
}

显然,你的实现看起来并不像这样,但它应该指向正确的方向。

免责声明:我根本不使用WinForms,因此上述内容可能不是应用的最佳解决方案,具体取决于其复杂程度等。

也可以尝试阅读本文,它可能会有所帮助:http://foyzulkarim.blogspot.co.nz/2012/09/using-dependency-injection-unity-to.html

相关问题