What I want is Simple Injector's equivalent of Autofac's tagged lifetimes:
I've read Simple Injector's documentation. The most probable way to accomplishing this is by using Simple Injector's custom lifestyles:
But the documentation on it is very sparse and I can't figure out how to get what I want from it. How can I get the equivalent of Autofac's tagged scopes in Simple Injector?
Example of something I would want:
// Arrange
var container = new Container();
container.Register<ICommand, ConcreteCommand>(new AsyncScopedLifestyle());
container.Register<IDBContext, ConcreteDbContext>(new AsyncScopedLifestyle("dbContext"));
using (AsyncScopedLifestyle.BeginScope(container))
{
// Act
var iCommandInstance1 = container.GetInstance<ICommand>();
IDBContext iDbContextInstance1 = null;
IDBContext iDbContextInstance2 = null;
using (AsyncScopedLifestyle.BeginScope(container, "dbContext"))
{
var iCommandInstance2 = container.GetInstance<ICommand>();
iDbContextInstance1 = container.GetInstance<IDBContext>();
// Call things that depend on IDBContext here
// Assert
Assert.IsTrue(object.ReferenceEquals(iCommandInstance1, iCommandInstance2));
}
using (AsyncScopedLifestyle.BeginScope(container, "dbContext"))
{
var iCommandInstance3 = container.GetInstance<ICommand>();
iDbContextInstance2 = container.GetInstance<IDBContext>();
// Call things that depend on IDBContext here
// Assert
Assert.IsTrue(object.ReferenceEquals(iCommandInstance1, iCommandInstance3));
}
Assert.IsFalse(object.ReferenceEquals(iDbContextInstance1, iDbContextInstance2));
}
In my case it would not make sense to have the two IDBContext
instances be the same.