开发者

Prism 4.0 : Overriding InitializeShell() Method

I've been going through the documentation for creating Prism applications and setting up the Shell seems to be split into 2 methods, CreateShell() and InitializeShell()

For CreateShell I simply have:

    protected override DependencyObject CreateShell()
    {
        return ServiceLocator.Current.GetInstance<Shell>();
    }

The documentation says that code is needed in the IntializeShell() method to ensure it is ready to be displayed. The following is given as an example:

    protected overrid开发者_如何学Goe void InitializeShell()
    {
        Application.Current.MainWindow = (Window)this.Shell;
        Application.Current.MainWindow.Show();
    }

I have noticed however that if I omit the first line and just call the Show() method it seems to work (MainWindow already appears to have Shell assigned to it). Can you tell me why this is the case, and why we still need to explicity set the MainWindow property here?

Also as I did not specifically register Shell to an interface within the container, how is it able to resolve Shell in CreateShell()?


Question 1: Why does just calling Show() seem to work and why is Application.Current.MainWindow seem to be populated?

There are a few things you should check here. In a typical WPF application, the type for the main window can be specified in the App.xaml. If it is specified, WPF will instantiate one of those for you. This is not desirable because WPF won't use your container to instantiate your shell and any dependencies won't be resolved.

When you run that first line of code in InitializeShell, you'd be replacing the WPF-instantiated Shell object with the one you manually instantiated.

I looked at the code for the MEF and Unity bootstrappers and I don't see anywhere that MainWindow is being set, but I don't know if you might have customized the base bootstrappers, so that's something else to look for.

Show() works because you are simply showing the window you instantiated and the WPF-instantiated one isn't shown. This is my theory, but without seeing your code, it'd be tough to say for sure.

Question 2: How can Unity resolve something that hasn't been registered?

Unity can always resolve a concrete type, regardless of registration. It cannot resolve non-concrete classes that haven't been mapped to a concrete type. This is why Resolve<Shell> works, but Resolve<IMyInterface> doesn't unless you register a type.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜