1

I keep getting reference to the same object. As you can see in constructor there are two objects with the same type. I would expect to get two different instances but whenever I set the property of _player1, the _player2 is being set accordingly with the same value. What am I doing wrong? Thanks

IoC container

public static void ConfigureContainer()
{
    var builder = new ContainerBuilder();

    builder.RegisterControllers(typeof(MvcApplication).Assembly);
    builder.RegisterInstance<IPlayer>(new Player());
    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

Controller constructor

public FlagGameController(IPlayer player1, IPlayer player2)
{
    _player1 = player1;
    _player2 = player2;
    _currentPlayer = player1;
}

2 Answers 2

2

when you say

 builder.RegisterInstance

you are actually setting it up to always return the same instance. If you want to return a different instance every time, use

 builder.RegisterType<Player>().As<IPlayer>().InstancePerDependency();

ref - http://docs.autofac.org/en/latest/lifetime/instance-scope.html#instance-per-dependency

0

The RegisterInstance method tells Autofac to register only a single instance of IPlayer inside the container, it allows you to register a singleton.

The following code

builder.RegisterInstance<IPlayer>(new Player());

is equivalent to

builder.RegisterInstance<IPlayer>(new Player()).SingleInstance();

or builder.RegisterType().As().SingleInstance();

See Registration Concepts - Instance components for more information.

If you want to have more than one instance, don't use the RegisterInstance method but use another registration method. For example

builder.Register(c => new Player()).As<IPlayer>(); 

or

builder.RegisterType<Player>().As<IPlayer>(); 

Autofac use the InstancePerDependency method by default which configure the registration to create a new instance each time it is resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.