MuriloKunze
MuriloKunze

Reputation: 15583

How to inject a new object every time it's needed?

I have this constructor:

public GroupController(IUserService userService, IGroupService groupService)
{
    _groupService = groupService;
    _userService = userService;
}

userService and groupService has the same object in constructor:

public UserService(IDb db)
{
     _db = db;
}

public GroupService(IDb db)
{
     _db = db;
}

and my container is this:

ObjectFactory.Initialize(x =>
{
    x.Scan(scan =>
    {
        scan.TheCallingAssembly();
        scan.WithDefaultConventions();
    });

    x.For<IDb>().Use<Db>();
    x.For<IUserService>().Use<UserService>();
    x.For<IGroupService>().Use<GroupService>();
});

So, How can I inject an IDb for UserService and an another IDb for GroupService because I can't use the same instance.

Upvotes: 0

Views: 154

Answers (1)

PHeiberg
PHeiberg

Reputation: 29811

The default lifecycle for StructureMap objects is PerRequestLifecycle, which means that multiple requests for the same interface within the same build session will resolve to a single instance. If you want it to resolve each interface request to a unique instance, you can use the UniquePerRequestLifecycle.

TL;DR: Configure your IDb like this:

x.For<IDb>.AlwaysUnique().Use<Db>();

Upvotes: 2

Related Questions