【发布时间】:2017-02-07 22:07:13
【问题描述】:
我正在尝试在 Unity 中设置注册,但无法准确获取所需内容。
假设我有以下定义:
public interface ISomeInterface { ... }
public interface ISomeDependency { ... }
public class DependencyA : ISomeDependency { ... }
public class DependencyB : ISomeDependency { ... }
public class SomeClassA : ISomeInterface
{
public SomeClassA(ISomeDependency dep){ ... }
}
public class SomeClassB : ISomeInterface
{
public SomeClassB(ISomeDependency dep){ ... }
}
然后我将它们注册到 Unity,如下所示:
Container.RegisterType<ISomeDependency, DependencyA>("DependencyA");
Container.RegisterType<ISomeDependency, DependencyB>("DependencyB");
Container.RegisterType<ISomeInterface, SomeClassA>("ClassA");
Container.RegisterType<ISomeInterface, SomeClassB>("ClassB");
我还注册了一个工厂,它将基于密钥构建ISomeInterface。
Container.RegisterType<Func<string, ISomeInterface>(new InjectionFactory(c=>
{
return new Func<string, ISomeInterface>(x=>
{
return c.Resolve<ISomeInterface>(x)
}
}));
(顺便说一句,如果有人知道创建密钥工厂的更好方法,我会欢迎提示)
如何配置 Unity,以便当 Unity 为我构建 SomeClassA 的实例时,它也会注入 DependencyA 的实例?同样,当 Unity 为我构建 SomeClassB 的实例时,它会注入一个 DependencyB 的实例。
感谢您的帮助。
编辑:纠正我的错字
【问题讨论】:
-
一旦你开始在同一个对象图中拥有同一个接口的多个实现,Pure DI 就成为一个更好的选择。查看这篇文章了解更多详情:criticalsoftwareblog.com/index.php/2015/08/23/…
-
使用工厂抽象(即使你使用
Func<T, R>)通常是a design smell。
标签: c# dependency-injection unity-container