0

我目前正在使用带有 Unity 的 Prism 开发 WPF 应用程序。该模型的功能被分成几个类库项目。对于每一组关注点,我都有一个实现项目和一个仅由接口和枚举组成的项目。目标是能够修改或完全替换实现 dll,而不会影响或不必修改应用程序中的任何其他内容。在这种情况下,我对如何在顶级应用程序中不硬引用两者的情况下将接口注册到它们的实现有点卡住了。

我知道它们必须在某个地方一起引用,但是在引导程序的顶级应用程序中发生这种情况是否违反最佳实践?对于这个特定问题,我是否应该研究 MEF 而不是 Unity?

4

1 回答 1

0

您通常在包含实现的模块中执行此操作。Unity 容器将在模块的构造函数中使用依赖注入提供;因此,Shell 永远不需要向接口实际注册实现。包含接口的模块通常是基础结构 DLL(而不是模块),因此可以被实现模块引用。

请注意,这符合 Prism 关于分离 DLL 之间的接口/实现的建议。他们在服务方面进行了一些深入的研究;尽管我怀疑您会找到将它们用于模型或其他对象的任何示例。

例子:

using Microsoft.Practices.Unity;
using YourInfrastructureDll;

public sealed class ModuleImplementationA : IModule
{
   private readonly IUnityContainer _container;

   public ModuleImplementationA(IUnityContainer container)
   {
      _container = container;
   }

   public void Initialize()
   { 
      // IYourInterface is defined in the Infrastructure DLL, while YourImplementationA exists in this module
      _container.RegisterType<IYourInterface, YourImplementationA>();
   }
}

这可以用另一个实现 DLL 换出:

using Microsoft.Practices.Unity;
using YourInfrastructureDll;

public sealed class ModuleImplementationB : IModule
{
   private readonly IUnityContainer _container;

   public ModuleImplementationB(IUnityContainer container)
   {
      _container = container;
   }

   public void Initialize()
   { 
      // IYourInterface is defined in the Infrastructure DLL, while YourImplementationB exists in a different module than the first
      _container.RegisterType<IYourInterface, YourImplementationB>();
   }
}
于 2011-01-05T16:07:10.870 回答