学习prism中关于依赖注入的一点小问题

longhui666888 2010-04-19 01:27:01
仿照prism中的EventAggregation例子做了个练习,建了两个Module的类库,其中有继承于IModule的ModuleA,ModuleB,我看附带的例子和网上的例子,有把构造函数写成
public ModuleA(IUnityContainer container, IRegionManager regionManager)的,也有写成
public ModuleA(IRegionManager regionManager, IEventAggregator eventAggregator)的。

然后在Bootstrapper中 Container.Resolve<ModuleA>()返回一个实例,我想知道传进构造函数的参数是从哪来的?是固定有几种写法呢,还是可以例用任何类型,任何个数的参数?

如果有人能说下Microsoft.Practices.Unity.dll中带的这个Container的原理和用法就更好了。多谢
...全文
437 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
longhui666888 2010-04-24
  • 打赏
  • 举报
回复
谢谢你
seeyou1997 2010-04-21
  • 打赏
  • 举报
回复
这些类Container都会帮你维护的,也就是说默认情况下都是同一个实例
longhui666888 2010-04-21
  • 打赏
  • 举报
回复
谢谢楼上的回复。请问使用.Resolve<ModuleA>()反回一个实例的时候,如果构造函数需要参数,Container会自动再生成一个参数么?如果参数的构造函数还需要参数,会不会这样递归下去?之所以这样想,是因为我想找到传进ModuleA的EventAggregator是从哪来的,可是却没发现。
seeyou1997 2010-04-20
  • 打赏
  • 举报
回复
RegisterInstance. This method registers with the container an existing instance of a type that you specify, with the lifetime that you specify. The container will return the existing instance during that lifetime. If you do not specify a value for the lifetime, the instance will have the default container-controlled lifetime. It will return a reference to the original object on each call to Resolve.


RegisterType. This method registers a type with the container. At the appropriate time, the container will build an instance of the type you specify. This could be in response to dependency injection, through class attributes, or when you call the Resolve method. The lifetime of the object it builds will correspond to the lifetime you specify in the parameters of the method. If you do not specify a value for the lifetime, the type is registered for a transient lifetime, which means that a new instance will be created on each call to Resolve.

我想你用的应该是RegisterInstance方法,并且没有指定lifetime,这样container就只会返回你注册的对象,如果你用RegisterType方法,那么container每次会返回不同的对象给你。

至于构造函数,应该是跟你的具体需要有关,如果你需要用到Container,EventAggregator或者RegionManager的时候,就放到你的构造函数里面
longhui666888 2010-04-19
  • 打赏
  • 举报
回复
网上有对Container的介绍,我也实验了一下,在Bootstrapper的protected override void InitializeModules()中,用Resolve方法返回了一个对象,得出一个结论:调用同一个Container的Resolve方法时,对于同一个类型,返回的是同一实例,这就是所谓的“单例模式”吧.

对于类的构造函数中的参数,Container也会自动以“单例”方式new一个出来么?太神奇了。求证实。

8,731

社区成员

发帖
与我相关
我的任务
社区描述
WPF/Silverlight相关讨论
社区管理员
  • WPF/Silverlight社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧