0

我有一个场景,我需要使用辅助类注入一个类型的实例。在我们的系统中,我们目前正在使用 Unity 将该对象注入到各个层中。

这是我目前拥有的:

container.RegisterInstance<ITest, new Test()>();

但不是那样,我想使用一个帮助类来为我创建实例:

container.RegisterInstance<ITest, Helper.GetITestIntance()>();
4

2 回答 2

6
container.RegisterType<ITest>(
    new ContainerControlledLifetimeManager(),
    new InjectionFactory(o => Helper.GetITestIntance()));
于 2012-08-23T08:41:32.443 回答
0

According to this: http://social.msdn.microsoft.com/Forums/en/wpf/thread/b71665b9-cc71-4c88-9776-6ccb4f871819 there does not seem to be a direct way. You can either register an instance that will be used, or register a "Type" that the container will instantiate on his own at some moments when it is required. There does not seem to be any way to register a "factory", nor the Type-registering methods do not take any delegates/callbacks..

There could be some way with use of Container Extensions - maybe you will be able to intercept the query for an instance and then provide your own response.. I think this a good place to start reading on it:

http://visualizationtools.net/default/unity-objectbuilder-part-i/
http://visualizationtools.net/default/unity-objectbuilder-part-ii/

edit: sorry, sorry, I've overlooked the LifetimeManager registration paramter. It seems this is exactly what you are looking for: http://tavaresstudios.com/Blog/post/Writing-Custom-Lifetime-Managers.aspx

So, write a factory in form of LifetimeManager, the creation would be done in GetValue method, and register a Type with your this Manager - and the Unity will ask the manager for object instances.

于 2012-08-23T08:17:34.040 回答