如何在Simple Injector中创建标记的Litetime?

时间:2019-06-26 14:50:32

标签: c# .net dependency-injection inversion-of-control simple-injector

我想要的是Simple Injector等效于Autofac的tagged lifetimes

我已经阅读了Simple Injector的文档。完成此操作的最可能方法是使用简单注入器的custom lifestyles

但是关于它的文档非常稀疏,我无法弄清楚如何从中获得想要的东西。如何在Simple Injector中获得与Autofac标记的作用域等效的内容?

我想要的例子:

// 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));
}

对于我来说,让两个IDBContext实例相同是没有意义的。

1 个答案:

答案 0 :(得分:0)

简单进样器不支持此功能。如果要通过自定义生活方式手动实现此功能,则必须重写大部分的Simple Injector。如果您确实需要此功能,请使用AutoFac或其他支持它的依赖项注入框架。

相关问题