how to create an instance of a class of another module without adding reference using prism in wpf

℡╲_俬逩灬. 提交于 2019-12-24 06:04:41

问题


I am working on WPF application using Prism 4.0 and MEF. I want to create an instance of class A of Module A in Class B of Module B and want to access properties and methods of Class A without adding any reference of Module A in Module B. I know that prism provide this functionality, but don't know how to do it.

We've specified all the assemblies in config file as follows:

<modules>
    <module assemblyFile="ModuleA.dll" moduleType="ModuleA.ModuleA, ModuleA, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" moduleName="ModuleA" startupLoaded="true"/>
    <module assemblyFile="ModuleB.dll" moduleType="ModuleB.ModuleB,ModuleB, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" moduleName="ModuleB" startupLoaded="true"/>
</modules>

All the assemblies gets loaded in the form of Menus in a ribbon panel.


回答1:


Normally you don't use the Prism IModule instances directly, they just serve as an entry point for the module dll. Continuing on that I'm assuming ModuleA.dll implements functionality somewhere that is needed in ModuleB.dll. This is indeed how Prism is used typically, but the solution to your problem is more related to MEF and dependency injection: basically you create an interface for whatever functionality you need, implement that interface in A and use the interface (i.e. without knowing/caring where and how it's implemented in B. Example:

in SharedInterfaces project

public interface IMenuStuff
{
  void DoSomething( .... )
}

in ModuleA project (which references SharedInterfaces project)

[Export( typeof( IMenuStuff ) ]
public class MenuStuff : IMenuStuff
{
  public void DoSomething( .... )
  {
    ...
  }
}

in ModuleB project (which also references SharedInterfaces project)

[ModuleExport( typeof( ModuleB )]
class ModuleB : IModule
{
  [Import]
  private IMenuStuff Menu { get; set; }

  public void Initialize()
  {
    //when reaching this point, and ModuleA was loaded properly
    //Menu will have been set by MEF to the instance exported in ModuleA
  }
}



回答2:


I think ther's no way to achieve that you need a reference to module A to use class A. AnyWay you can try to use Interfaces :

Interfaces (C# Programming Guide)

Interface Properties (C# Programming Guide)



来源:https://stackoverflow.com/questions/18530203/how-to-create-an-instance-of-a-class-of-another-module-without-adding-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!