Question

If I register a type with RequestScope.Request, and then I autowire it in a service, I know the object's lifetime scope will be respected.

Will this also hold true if I resolve the type in a non auto wired way, i.e.:

var authRepo = EndpointHost.TryResolve<IAuthenticationRepository>();

Also how can I confirm this? Thanks

Was it helpful?

Solution

Will the lifetime scope be respected when using TryResolve instead of autowire? Yes.

You can confirm this by setting up a project where you test the lifetime of a dependancy. I created a test project to demonstrate this.

Full source code here.

I created 4 dependancies; 2 which are auto wired, consisting of a dependancy that will persist (static) across all requests, and the other which will only last for the request. The other 2 dependancies are created with the same respective ReuseScopes but they, are not autowired and will be resolved in using the TryResolve method. Thus:

container.RegisterAutoWiredAs<AutoStatic, IAutoStatic>();
container.RegisterAutoWiredAs<AutoRequest, IAutoRequest>().ReusedWithin(ReuseScope.Request);
container.Register<IResolveStatic>(c => new ResolveStatic());
container.Register<IResolveRequest>(c => new ResolveRequest()).ReusedWithin(ReuseScope.Request);

When each of the dependancies are created, their constructor method sets the time they where created on the CreatedAt property.

public class AutoStatic : IAutoStatic
{
    public string CreatedAt { get; set; }
    public AutoStatic() { CreatedAt = DateTime.Now.ToString(); }
}

    ...

The static dependancies i.e. ReuseScope.Default should always show the time of first request on all requests. The dependancies scoped as ReuseScope.Request should always have a new creation time on each request.

So our simple service that will prove this is:

public class TestController : Service
{
    public IAutoStatic AutoStatic { get; set; }
    public IAutoRequest AutoRequest { get; set; }
    IResolveStatic ResolveStatic { get; set; }
    IResolveRequest ResolveRequest { get; set; }

    public void Get(TestRequest request)
    {
        ResolveStatic = EndpointHost.TryResolve<IResolveStatic>();
        ResolveRequest = EndpointHost.TryResolve<IResolveRequest>();

        Console.WriteLine("-NEW REQUEST-");
        Console.WriteLine("Auto Static {0}", AutoStatic.CreatedAt);
        Console.WriteLine("Resolve Static {0}", ResolveStatic.CreatedAt);
        Console.WriteLine("Auto Request {0}", AutoRequest.CreatedAt);
        Console.WriteLine("Resolve Request {0}", ResolveRequest.CreatedAt);
    }
}

The results:

Output

So after 3 different requests, using both the autowire and the TryResolve method, we see that the static work as expected and the Request scoped likewise.

So use autowire or TryResolve the ReuseScope is respected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top