Unity Container: Use the default ContainerControlledLifetimeManager for the Resolve Method Group

How to complete TODO to pass this test?

class MyClass { }

[Test]
public void Singleton_by_default_test()
{
    var parentContainer = GetUnityContainer();        
    var container = parentContainer.GetChildContainer();

    // TODO: Add magic here (but do NOT explicitly register MyClass in container!)

    Assert.AreSame(container.Resolve<MyClass>(), container.Resolve<MyClass>());
}

Update: There is a method that uses inheritance.

public class SingletonContainer : UnityContainer
{
    public override object Resolve(Type t, string name)
    {
        var obj = base.Resolve(t, name);
        RegisterInstance(t, name, obj, new ContainerControlledLifetimeManager());
        return obj;
    }
}

I use container.GetChildContainer () to get a container instance, so this method does not assign me.

+3
source share
2 answers

I see where you are going with this. An interesting problem.

, , , Unity. , , : http://msdn.microsoft.com/en-us/library/dd140062.aspx

Unity " " . - LifetimeStrategy.

LifetimeStrategy, , , ContainerControlledLifetimeManager . LifetimeStrategy, ContainerControlledLifetimeManager .

:

public class MakeEverythingSingletonStrategy : BuilderStrategy
{
     public override void PreBuildUp(IBuilderContext context)
     {
          Type objectType = BuildKey.GetType(context.BuildKey);
          context.PersistentPolicies.Set<ILifetimePolicy>(
                  new SingletonLifetimePolicy(), 
                  context.BuildKey);

     }
}

Configure<T>, , .

, Stackoverflow BuilderStrategy:

factory Unity

+4

singleton. MyClass: *

<type type="MyClass" mapTo="MyClass">
  <lifetime type="singleton" />
</type>
0

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


All Articles