Question

My question is quite simple. I have to register all implementations by their interface and concrete types.

container.RegisterAutoWiredAs<AuthenticationManager, IAuthenticationManager>();
container.RegisterAutoWired<AuthenticationManager>();

I am using default singleton lifecycle. I want to make sure they resolve to same instance but my test shows I end up with two instances.

if (!ReferenceEquals(container.Resolve<IAuthenticationManager>(),
                     container.Resolve<AuthenticationManager>()))
{
    throw new ApplicationException("multiple instances");
}

Is there way to use a single instance here?

Was it helpful?

Solution

Registering it twice causes a new instance for each type to be created, one for the interface and once for the concrete type.

If you want the same singleton instance you would first register an autowired instance and then just register against the other type resolving the same instance, e.g:

container.RegisterAutoWiredAs<AuthenticationManager, IAuthenticationManager>();

and either

container.Register(c => (AuthenticationManager)c.Resolve<IAuthenticationManager>());

or

var instance = (AuthenticationManager)container.Resolve<IAuthenticationManager>();
container.Register(instance);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top