Search code examples
c#scopeautofaclifetimeobject-lifetime

How to specify a child scope for constructor func factory parameter?


I want to do something like:

class MyClass
{
    Func<OtherClass> _factory;
    public MyClass([WithChildScope("OtherClassScope")] Func<OtherClass> other)
    {
        _factory = other;
    }

    public OtherClass LoadOther(int id)
    {
        var entity = DbHelper.LoadEntity(id);
        var other = _factory();
        other.Configure(entity);
        return other;
    }
}

So that each call to LoadOther should create a new OtherClass instance with its own scope (inside a parent scope in which MyClass was constructed). But there is no [WithChildScope] attribute.

In NInject I would use DefinesNamedScope with ContextPreservation.

Can I do it in AutoFac without passing locator everywhere?


Solution

  • So I found the solution myself:

    k.RegisterType<Scoped<UserScope>>().AsSelf().WithParameter("childTag", "User");
    
    public class Scoped<T>
    {
        public Scoped(ILifetimeScope scope, object childTag)
        {
            Value = scope.BeginLifetimeScope(childTag).Resolve<T>();
        }
    
        public T Value { get; }
    }
    
    public class UserRepository
    {
        Func<Scoped<UserScope>> _factory;
    
        public UserRepository(Func<Scoped<UserScope>> factory)
        {
            _factory = factory;
        }
    }