Unity and Life Cycle Management

I do not know how to describe it well, but here.

I have 4 classes: A, B, C, D.

A is administered B, C, D
C is introduced D

A - for the decision.
B - singleton.
C and D I do not know.

I want A and C to use the same instance of D, so every time I allow A from the container, D needs to be created once and entered in both A and C.

The easiest way is to simply pass D to C without using Unity. But is there a way to do this with Oneness? I use ContainerControlledLifetimeManager and PerResolveLifetimeManager and never a child container, which I suspect might be useful. I will play a little with this, but it turns out pretty dirty. Can this be done easily?

+3
source share
3 answers

Is there a bigger context in which you work? In ASP.NET, I created a PerRequestLifetimeManager that returns the same object when it is requested multiple times during the same HTTP request.

EDIT: Implementation is implemented here, if you're interested.

public class PerRequestLifetimeManager : LifetimeManager
{
    private readonly object key = new object();

    public override object GetValue()
    {
        if (HttpContext.Current != null && HttpContext.Current.Items.Contains(key))
            return HttpContext.Current.Items[key];
        else
            return null;
    }

    public override void RemoveValue()
    {
        if (HttpContext.Current != null)
            HttpContext.Current.Items.Remove(key);
    }

    public override void SetValue(object newValue)
    {
        if (HttpContext.Current != null)
            HttpContext.Current.Items[key] = newValue;
    }
+11
source

So you want to split D between A and C when A is allowed. How about when something else resolves?

If it's just one instance of D everywhere, which is ContainerControlledLifetimeManager.

D , D PerResolve ContainerControlled . , A C, D .

- , .

, , .

0

MVC3, Unity.Mvc3 http://unitymvc3.codeplex.com

: ", Microsoft IOS IOC ASP.NET MVC 3. DependencyResolver, HTTP- IDisposable ".

http://www.devtrends.co.uk/blog/integrating-the-unity.mvc3-1.1-nuget-package-from-scratch

0

Source: https://habr.com/ru/post/1786671/


All Articles