您通常在包含实现的模块中执行此操作。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>();
}
}