0
votes

I'm wondering how I do the following with Unity....

I've got a simple bit of code where an object is created "per request", in most cases I use an injection factory to build the ILogger instance (per request)... as follows...

container.RegisterType<ILogger>(new InjectionFactory( factory => factory.Resolve<ILoggingFactory>() ));

Quite simple so far... but imagine I have multiple calls to multiple objects in a single web request, when the request comes in I want to create and use the logger as above, but I want subsequent calls to use to the instance that already exists.... As follows

// This should use the RegisterType functionality (above) to create a new instance of the logger
public class A : IAIntf
{
    public AConstructor(ILogger log)
    { .. }
}

// This should use the logger which was constructed when A was created
public class B : IBIntf
{
    public BConstructor(ILogger log)
    { .. }
}

This code correctly creates an interface for class A, but fails to reuse the interface when creating class B, using ..

unity.GetService(typeof(T)); // Unity thinks T is IBIntf (which is correct)

.. but during the resolution Unity fails to reuse the ILogger class created when class A was instantiated.

I think the problem is that Unity needs to maintain a lifetime for the ILogger interface so I have adjusted the container registration as follows, but a new ILogger is created :(

container.RegisterType<ILogger>(new HttpRequestLifetimeManager<ILogger>(), 
    new InjectionFactory( factory => factory.Resolve<ILoggingFactory>() ));

// Also tried
container.RegisterType<ILogger>(new PerResolveLifetimeManager(), 
    new InjectionFactory( factory => factory.Resolve<ILoggingFactory>() ));

How do I tell unity to give me a new instance of class B, but reusing the ILogger interface that was also passed to class A, instead of creating a new ILogger instance ?

1

1 Answers

0
votes

I think I've managed to solve this - I think my problem was that HttpContext.Current is inside a class library so does not seem to resolve properly, using a callcontext instead seems to solve the issue.