Unity框架不解析OptionalDependency

问题描述 投票:0回答:1

我正在Unity 5和Prism 7上构建一个程序。我希望我的程序是高度模块化的,所以如果某些模块不可用,我希望它能正常运行。

为此,我想用[OptionalDependency]属性标记可选的依赖项,并让一个类与它们一起决定如果在构造函数中传递null该怎么做。

但是如果我用这个属性标记一个依赖项,Unity就不会解析它而只是传递null而不是依赖实例,尽管模块像往常一样可用。

如何让依赖变得非常好?

或者另一种选择,如何在不能解决依赖关系的情况下让Unity不抛出,而只是传递null并让构造类决定该怎么做?

我的节目有App.xaml.cs

public partial class App : PrismApplication
{
    protected override Window CreateShell()
    {
        InitializeModules();
        this.ShutdownMode = ShutdownMode.OnMainWindowClose;
        var shell = Container.Resolve<Shell>();
        this.MainWindow = shell;
        return shell;
    }

    protected override void RegisterTypes(IContainerRegistry containerRegistry) { }

    /// <summary>
    /// Creating catalog of Modules from .dlls in "Modules" folder
    /// </summary>
    protected override IModuleCatalog CreateModuleCatalog()
    {
        var catalog = new DirectoryModuleCatalog() { ModulePath = @"./Modules" };
        catalog.Initialize();
        // by the way, modules aren't getting recognized without
        // catalog.Initialize() or InitializeModules in CreateShell.
        // Should it be such as that? Seems to me like no..
        return catalog;
    }
}

除了主要问题,我感谢任何关于如何在问题的评论中使我的代码更好的建议,因为我是Prism + Unity的菜鸟。谢谢!

c# unity-container prism
1个回答
0
投票

这种方法不是一个好主意。构造函数注入意味着需要依赖项。另外,我不认为OptionalDependencyAttribute在ctor中工作,而是必须应用于属性。尝试制作属性并将属性应用于该属性。

不需要CreateShell方法中的所有代码。只是return Container.Resolve<Shell>()就是这样。

此外,未加载的模块是一个已修复的错误,可在MyGet上的最新Prism CI biuld中获得。

© www.soinside.com 2019 - 2024. All rights reserved.