开发者

Weak reference vs. Autofac resolve?

I have POCO objects that reference each other by findi开发者_StackOverflow中文版ng ID's in repositories. I don't want the objects to have strong references between each other because the repositories have cache policy that might evict objects. Other objects that reference them should just reload them via the repository. I am using AutoFac as my IoC container.

Very simple example - a Region object references to a Currency object:

class Region
{
    ...
    public Currency GetCurrency()
    {
        ... Get the right Currency object
    }
    ...
}

I have been experimenting with two ways to do this. The first is asking AutoFac to resolve the Currency repository every time so I can call Find(id).

The 2nd is WeakReference, where I check .IsAlive to see if I can just return .Target or if I need to resolve the repository and call Find, and make a WeakReference to what I got.

I have been studying up on the small overhead that WeakReference imposes but i am ont sure how that compares to asking AutoFac to resolve every time.

Thoughts?

Edit: Taking the whatever time/effort the repository needs to answer the .find - I'm more interested in which is more expensive, WeakReference with its overhead or AutoFac resolution.


I'm just wondering which is more overhead - WeakReference or repeated IoC resolutions for the repositories.

This is hard to answer, because the two do entirely different things. The overhead is also quite dependent on how you will be registering / resolving the component with autofac.

For example: Are you planning on registering as InstancePerLifetimeScope(), and getting a referency to a Lazy?

With weakreference, you are holding a reference to an object, but telling the runtime that it's okay to collect it - you'll deal with that.

With autofac, you are asking a container to construct and provide instances, inject dependencies, as well as (possibly) managing lifetime scope and disposal.

So as far as overhead - the small area where these two concerns intersect ( get an instance of something) is entirely dependent on how you register and resolve the component, but I don't see any codepath where the WeakReference wouldn't have slightly (very slightly) less overhead. The WR has a bit more runtime overhead, though - so it's hard to compare directly.


Going to the database is always going to be far more overhead than dealing with a weakreference. For this particular example of currencies, there are only a handful of objects so you'd be best served by keeping them all in memory but for larger datasets, the 2-tiered approach (weakreference+repository) seems reasonable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜