Question

I am writing a adapter around autofac, and need to provide an implementation of:

T ResolveSingleton<T>()

where this method will return an instance if and only if the type was registered with singleton lifetime, otherwise it will throw an error.

I am new to autofac and was wondering if there is a way to query the container for the registered lifetime of a type?

Thanks!

Was it helpful?

Solution

Looking at the Autofac source code, you'll can see that the implementation of SingleInstance is this:

    public IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> SingleInstance()
    {
        RegistrationData.Sharing = InstanceSharing.Shared;
        RegistrationData.Lifetime = new RootScopeLifetime();
        return this;
    }

So you'll have to check the ComponentRegistry for registrations matching those qualities.

    public T ResolveSingleton<T>()
    {
        IComponentRegistration reg;
        if (_context.ComponentRegistry.TryGetRegistration(new TypedService(typeof (T)), out reg))
        {
            if (reg.Lifetime is RootScopeLifetime && reg.Sharing == InstanceSharing.Shared)
                return (T) _context.ResolveComponent(reg, Enumerable.Empty<Parameter>());
        }

        throw new Exception();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top