Domanda

I have configured 2 object instance into structuremap

x.ForRequestedType<IStayOnTillAppDies>().TheDefaultIsConcreteType<StayOnTillAppDies>().CacheBy(InstanceScope.Singleton);

x.ForRequestedType<IDiesWhenRequestObjectDies>().TheDefaultIsConcreteType<DiesWhenRequestObjectDies>().CacheBy(InstanceScope.PerRequest);

As you can see one is singleton/shared scoped object while another is PerRequest.

Singleton object StayOnTillAppDies will stay alive till app is killed while PerRequest object DiesWhenRequestObjectDies is supposed to get cleanup from memory when the requesting scope dies.

I need to use object DiesWhenRequestObjectDies in StayOnTillAppDies so its being injected accordingly using Constructor Injection.

public class StayOnTillAppDies : IStayOnTillAppDies 
{
  private readonly IDiesWhenRequestObjectDies   _diesWhenRequestObjectDies;

  public StayOnTillAppDies (IDiesWhenRequestObjectDies diesWhenRequestObjectDies)
  {                       
    _diesWhenRequestObjectDies = diesWhenRequestObjectDies;
  }

  ....
  ....
  ....
}

_diesWhenRequestObjectDies is required only at one or two place in StayOnTillAppDies but here injected object will never get released because StayOnTillAppDies is of Singleton scope.

How can we handle this to ensure that PerRequest objects are kept only for the requested period and become ready-for-collection later?

È stato utile?

Soluzione

You use delegate injection to solve this problem.

public class StayOnTillAppDies : IStayOnTillAppDies
{
    private readonly Func<IDiesWhenRequestObjectDies> resolver;

    public StayOnTillAppDies(Func<IDiesWhenRequestObjectDies> resolver)
    {
        this.resolver = resolver;
    }
}

Use the following code in the StayOnTillAppDies class when you require an instance of IDiesWhenRequestObjectDies

IDiesWhenRequestObjectDies instance = this.resolver();

This is the configuration I used to set it up.

IContainer container = new Container(x =>
    {
        x.ForRequestedType<IStayOnTillAppDies>()
            .TheDefaultIsConcreteType<StayOnTillAppDies>()
            .CacheBy(InstanceScope.Singleton);

        x.ForRequestedType<IDiesWhenRequestObjectDies>()
            .TheDefaultIsConcreteType<DiesWhenRequestObjectDies>()
            .CacheBy(InstanceScope.PerRequest);
    });

container.Configure(x =>
    {
        x.SelectConstructor<StayOnTillAppDies>(() =>
            new StayOnTillAppDies(() => 
                container.GetInstance<IDiesWhenRequestObjectDies>()));
    });
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top