Autofac - resolving dependencies in multi thread environment

冷暖自知 提交于 2019-12-04 07:57:34

To give each thread its own lifetime scope, you just need to register your IsolatedLifetimeScopeFactory as SingleInstance. This will solve your concerns 2) and 3)

[TestMethod]
public void MyTestMethod()
{
    var cb = new ContainerBuilder();
    cb.RegisterGeneric(typeof(IsolatedLifetimeScopeFactory<>))
        .SingleInstance();
    var container = cb.Build();

    using (var scope1 = container.BeginLifetimeScope("scope1"))
    using (var scope2 = scope1.BeginLifetimeScope("scope2"))
    {
        var factory = scope2.Resolve<IsolatedLifetimeScopeFactory<object>>();
        var tag = factory._scope.Tag; // made _scope public for testing purposes
        Assert.AreNotEqual("scope1", tag);
        Assert.AreNotEqual("scope2", tag);

        // This particular string "root" is probably not guaranteed behavior, but
        // being in the root scope is guaranteed for SingleInstance registrations.
        Assert.AreEqual("root", tag);
    }
}

Your concern 1) could be solved by using a different abstraction. For example, you could add this to the IsolatedLifetimeScopeFactory

public Autofac.Features.OwnedInstances.Owned<TA> Create()
{
    return _scope.Resolve<Autofac.Features.OwnedInstances.Owned<TA>>();
}

And you could hide Owned behind an abstraction if you really wanted to, although I would say that's overkill.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!