开发者

Lazy dependency registration with unity

Note 1: I want to make this clear: I am not trying to lazy load dependencies or inject lazy types.

Most (all?) IoC containers require metadata to be registered with the container to describe how some type should be resolved when asked; this includes the implementation of an interface, the lifetime of the object, etc. Over the past couple of years, the fluent/convention based APIs have been added to most (all?) IoC containers which reduces a lot of the noise when providing this metadata to the container.

With ninject, I am using a conventions based approach to register my metadata, but I do it on demand, not upfront. This yields huge performance savings in an integration test scenario where you are creating ~10 objects; you lose the overhead of having to register the entire application's dependencies every test.

Note 2: Please do not tell me that you should not use an IoC container in an integration test.

There is some pressure to move to using Microsoft components when available, so Unity is on my horizon. I have the conventions based registration working, but I cannot figure out how to "discover" this metadata on demand/lazily like I could in Ninject.

My first attempt to implement this was using a wrapper around the UnityContainer instance, and upon calling GetInstance(type) on the wrapper, I can query the container to see if the type is registered. If not, I can invoke my conventions, discover the metadata, and register the type. This approach only goes one level deep开发者_如何学运维 however; if that type is injected with more dependencies, each dependency does not get fed back into the GetInstance(type) method, and thus, my dilemma.

The question: How can I lazily/on-demand add type registrations to Unity?

Source would be nice, but a pointer to a hook in the container would be just as good. I tried inheritance but there is nothing to override like in Ninject.


First of all - every problem with Unity can, and should be solved by avoiding using it.

If that's not an option, I think there's no option in Unity to register stuff on demand.

As a sidenote, I would still not default to trying to register stuff lazily. The fact that it yields unacceptable performance with one container doesn't mean that would be the case with another. Have you measured it first?

I use container (Windsor) a lot in tests and I never found up-front registration to be a problem. More over, (I know that those are tests so different rules apply) I think not registering stuff upfront is wrong. Most containers I'm aware of even if allow this, are still heavily optimised for up-front registration so your performance gain could be zero, or even you could find yourself seeing worse numbers than doing it the right way and registering upfront.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜