With interfaces and implementations in separate assemblies, where should Unity map the two in a Prism WPF application?

StackOverflow https://stackoverflow.com/questions/4599494

سؤال

I am currently working on a WPF application using Prism with Unity. The model's functionality is split up into several class library projects. For each group of concerns, I have one implementation project and one project consisting only of interfaces and enums. The goal is to be able to modify or completely replace an implementation dll without affecting or having to modify anything else in the application. This being the case, I'm a little stuck on how to register interfaces to their implementation without hard references to both in the top level application.

I know they will have to be referenced together somewhere, but is it against best practices to have that occur in the top level app within the bootstrapper? Should I instead be looking into MEF rather than Unity for this particular problem?

هل كانت مفيدة؟

المحلول

You typically do this in the module containing the implementations. The Unity container will be provided using dependency injection in the module's constructor; hence, the Shell never needs to actually register the implementations with the interface. The module containing the interfaces is usually an infrastructure DLL (and not a module), and hence can be referenced by the implementation modules.

Note that this is in line with Prism's recommendations regarding seperation of interface / implementation between DLLs. They go into it in some depth with respect to services; although I doubt you'll find any examples of them using it for models or other objects.

Example:

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>();
   }
}

This can be swapped out with another implementation 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>();
   }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top