Unity 1.2 内部类型的依赖注入
我在一个库中有一个外观,它通过一个简单的界面公开一些复杂的功能。我的问题是如何为外观中使用的内部类型进行依赖注入。假设我的 C# 库代码如下 -
public class XYZfacade:IFacade
{
[Dependency]
internal IType1 type1
{
get;
set;
}
[Dependency]
internal IType2 type2
{
get;
set;
}
public string SomeFunction()
{
return type1.someString();
}
}
internal class TypeA
{
....
}
internal class TypeB
{
....
}
我的网站代码如下 -
IUnityContainer container = new UnityContainer();
container.RegisterType<IType1, TypeA>();
container.RegisterType<IType2, TypeB>();
container.RegisterType<IFacade, XYZFacade>();
...
...
IFacade facade = container.Resolve<IFacade>();
这里facade.SomeFunction() 抛出异常,因为facade.type1 和facade.type2 为null。任何帮助表示赞赏。
I have a facade in a library that exposes some complex functionality through a simple interface. My question is how do I do dependency injection for the internal types used in the facade. Let's say my C# library code looks like -
public class XYZfacade:IFacade
{
[Dependency]
internal IType1 type1
{
get;
set;
}
[Dependency]
internal IType2 type2
{
get;
set;
}
public string SomeFunction()
{
return type1.someString();
}
}
internal class TypeA
{
....
}
internal class TypeB
{
....
}
And my website code is like -
IUnityContainer container = new UnityContainer();
container.RegisterType<IType1, TypeA>();
container.RegisterType<IType2, TypeB>();
container.RegisterType<IFacade, XYZFacade>();
...
...
IFacade facade = container.Resolve<IFacade>();
Here facade.SomeFunction() throws an exception because facade.type1 and facade.type2 are null. Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不推荐注入内部类。
我将在程序集中创建一个公共工厂类,其中声明了内部实现,可用于实例化这些类型:
并且 XYZFacade 中的依赖项将与 FactoryClass 类一起使用:
如果要使其可测试,请为以下对象创建一个接口:工厂类。
Injecting internal classes is not a recommended practice.
I'd create a public factory class in the assembly which the internal implementations are declared which can be used to instantiate those types:
And the dependency in XYZFacade would be with the FactoryClass class:
If you want to make it testable create an interface for the FactoryClass.
如果容器创建代码位于内部类型的程序集之外,则 Unity 无法查看和创建它们,因此无法注入依赖项。
If the container creation code is outside the assembly of the internal types, Unity can't see and create them and thus can't inject the dependecies.