簡體   English   中英

PRISM:使用 MVVM,如何解析或注入構造函數對象?

[英]PRISM: Using MVVM, how to resolve or inject in a constructor objects?

我正在使用 MVVM 和 PRISM。 在項目中,我有一個名為 IFoo 的通用接口,其他模塊應該實現這個接口並注冊它。

// Common module
public interface IFoo { }

// Module1 module
public class Foo1 : IFoo { }

然后當我初始化 module1 時,我注冊我的類型並導航。

_container.RegisterType<IFoo, Foo1>(new ContainerControlledLifetimeManager());
_container.RegisterType<Object, View1>("View1");

var module = new Uri("View1", UriKind.Relative);
_regionManager.RequestNavigate("MainRegion", module);

View1 構造函數包含 viewModel,此視圖 model 在其構造函數中具有:

    public ViewModel1(IFoo foo, IEventAggregator eventAggregator, IRegionManager regionManager)
    {
        ...
    }

到此為止,沒關系。 但稍后,我需要從外部模塊獲取 Foo1。 因此,我將另一個注冊表設置為 Foo1 的映射名稱:

_container.RegisterType<IFoo, Foo1>(new ContainerControlledLifetimeManager());
_container.RegisterType<IFoo, Foo1>("foo1", new ContainerControlledLifetimeManager());

是的,它對我有用,但我不喜歡將兩個實例分開的想法。 我只需要一個,並訪問同一個實例。

有沒有辦法解決這種情況? 提前致謝。

無論如何,我附上了一個 Zip,其中包含一個代表我的問題的演示。 http://www.mediafire.com/?feod8x0b952457e

加載模塊時,您可以在引導程序中注冊所有類型。

// register all modules
protected override void ConfigureModuleCatalog()
{
    // get all module types
    var types = new List<Type>();
    types.Add(typeof(ModuleA));
    types.Add(typeof(ModuleB));
    types.Add(typeof(ModuleC));

    // register all types
    foreach (var type in types)
    {
        ModuleCatalog.AddModule(new ModuleInfo()
        {
            ModuleName = type.Name,
            ModuleType = type.AssemblyQualifiedName
        });
    }
}

然后在ConfigureContainer中,您 map 稍后要訪問的所有類型和/或實例。 配置的容器被傳遞到 Module1Module 的構造函數中。

// register all types in all modules
protected override void ConfigureContainer()
{
    base.ConfigureContainer();

    // ModuleA
    Container.RegisterType<IInterface1, Type1>();
    Container.RegisterType<IInterface2, Type2>();

    // ModuleB
    Container.RegisterInstance<IInterface3>("name", new Type3());
    Container.RegisterType<IInterface4, Type4>();

    // ModuleC
    Container.RegisterType<IInterface5, Type5>();
    Container.RegisterType<IInterface6, Type6>();
}

我認為您不需要注冊 Foo1 兩次。 您正在使用ContainerControlledLifetimeManager ,因此任何時候您向 Unity 容器請求 IFoo 實例時,它都會為您提供 Foo1 - 您不需要使用名稱作為鍵。

所以,在module1中你注冊了 Foo1:

_container.RegisterType<IFoo, Foo1>(new ContainerControlledLifetimeManager());
System.Diagnostics.Debug.Print(Foo1.GetHashCode());

在你的外部模塊中:

IFoo someFoo = _container.Resolve<IFoo>();

// someFoo is the same object as Foo1, so the hashcodes will be equal.
System.Diagnostics.Debug.Print(someFoo.GetHashCode());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM