我可以在一个项目中使用 RegisterType 并使用 Unity Containers 在另一个项目中解析此接口吗?

Can I do a RegisterType in one project and Resolve this interface in another project using Unity Containers?

我有一个 VS 解决方案 A,其中包含一个接口 foo

public interface IFoo
{
 //some methods
}

我有一个实现此接口的解决方案 B

public class Bar : IFoo
{ 
  //methods implemented here
}

App.xaml.cs 在解决方案 B 中使用 unity 容器来注册这个

App.xaml.cs

//代码

this.unityContainer.RegisterType<IFoo, Bar>();

现在在解决方案A中,我可以解析IFoo吗?

SOLn A

Class A
{
   this.unityContainer.resolve<IFoo>(); //get error here
}

由于类型IFoo, Bar没有在同一个解决方案中注册,我得到一个类型无法解析的错误。是否有使这成为可能的解决方法?

只要您在项目之间“共享”一个 unity 容器,您注册的项目没有区别。

这是注册依赖项的标准方式 - 但请记住!您必须以某种方式共享 ioc 容器实例。

例子

#项目A(无依赖)

interface IFoo {}

#项目B(依赖A)

unityContainer.RegisterType<IFoo, Bar>();

#项目C(依赖A)

unityContainer.resolve<IFoo>();

但是同样,您必须以某种方式共享 UnityContainer 实例。通常有 Main 个项目充当这些项目之间的“粘合剂”。

我可以推荐一本关于依赖注入的好书: https://www.manning.com/books/dependency-injection-principles-practices-patterns

因为你必须了解基本原理和机制。