Resolve component in both tagged scope and untagged scope

前端 未结 2 1843
轻奢々
轻奢々 2021-01-23 04:01

I\'m try to supply a different service to some tagged lifetime scopes in AutoFac, but can\'t seem to get the hang of it.

I\'ve tried using the custom lifetime from Insta

2条回答
  •  温柔的废话
    2021-01-23 04:48

    The solution could be to provide these custom services for the lifetime scope when you create the scope. When creating a new lifetime scope with container.BeginLifetimeScope you can provide additional Action parameter to define some custom registrations for this particular lifetime scope.

    So, for your code, instead of global registration for ChildB, you could move it to per-scope registration. It could look something like that:

    [TestMethod]
    public void NamedLifetimeTests()
    {
        var builder = new ContainerBuilder();
        builder.Register(c => new ChildA()).As().InstancePerLifetimeScope();    
    
        var container = builder.Build();
        using (var scope = container.BeginLifetimeScope())
        {
            var parent = scope.Resolve();
            Assert.IsTrue(parent.GetType() == typeof(ChildA));
        }
    
        using (var scope = container.BeginLifetimeScope("system"), cb => { cb.RegisterType().As(); }))
        {
            var parent = scope.Resolve();
            Assert.IsTrue(parent.GetType() == typeof(ChildB));
        }
    }
    

    EDIT: Avoiding injecting lifetime scope is understandable. Another solution could be picking proper implementation, based on lifetime scope tag, similar to selection of implementation based on parameter, described in docs:

    // omitted ...
    var builder = new ContainerBuilder();
    builder.Register(c =>
        {
            var currentScope = c.Resolve();
            if (currentScope.Tag?.ToString() == "system")
            {
                return new ChildB();
            }
    
            return new ChildA();
        }).InstancePerLifetimeScope();   
    
    var container = builder.Build();
    // omitted ...
    

提交回复
热议问题