开发者

Dependecy injection(Windsor) on WPF UserControl

Using DI into MainView is not problem: I added my windows into my container and on start up I show my windows that has been pulled out from my container. But If I have a usercontrol added into my main view as xaml tag, wpf view engine it will create automatically new instance for it without pulling out the UserControl I added into my container as well.. How can I force WPF view engine to search compon开发者_StackOverflow中文版ent required by view/xamal into my container instead of creating new one?


There is no way to do it without modifying your XAML. You can think about some workarounds, for example create a control inherited from ContentControl which will inject dependencies into its Content but I would not recommend this approach, only if you have no choice.

What I would recommend is to use the best WPF pattern - MVVM. The idea is to have a hierarchy of ViewModels, all of them will be created using IoC container with proper constructor injection. Also you will have hierarchy of views, each view will depend only on corresponding viewModel which will be passed into view's DataContext. This approach will allow you to use DI in WPF application nicely.


I think I understood what you suggested me

<Window x:Class="DDDSample02.Wpf.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:presentation="clr-namespace:DDDSample02.Wpf.Views"
        Title="MainWindow" Height="384" Width="821">
    <Grid>
        <presentation:ProductsView DataContext="{Binding Path=ProductsPresenter}" />
    </Grid>
</Window>

where MainWindow is pulled out from container at startup

protected override void OnStartup(StartupEventArgs e)
{
    GuyWire.Wire();
    ((Window)GuyWire.GetRoot()).Show();//MainWindow
}

and Mainwindow looks like

public partial class MainWindow : Window
{

    public MainWindow(DDDSample02.ViewModel.MainWindowPresenter presenter)
    {
        InitializeComponent();
        this.DataContext = presenter;
    }

}

public class MainWindowPresenter
{
    public MainWindowPresenter(ProductsPresenter productPresenter)
    {
        this.ProductsPresenter = productPresenter;
    }

    public ProductsPresenter ProductsPresenter { get; private set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜