2

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.

Steven
  • 166,672
  • 24
  • 332
  • 435
NomenNescio
  • 2,899
  • 8
  • 44
  • 82
  • There is no equivalent in Simple Injector. Please provide us with an example of what it is you are trying to achieve, and why. – Steven Jun 26 '19 at 16:19
  • @Steven Provided an example. – NomenNescio Jun 27 '19 at 09:21
  • Thank you for providing an example. Unfortunately, what you are describing is the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Can you instead explain *the actual problem*? – Steven Jun 27 '19 at 11:14

1 Answers1

0

Simple Injector does not support this feature. If you want to implement this feature manually with custom lifestyles, you'll have to rewrite a large part of Simple Injector. If you really want this feature, use AutoFac, or some other dependency injection framework that supports it.

NomenNescio
  • 2,899
  • 8
  • 44
  • 82