Skip to content

How to obtain a lifetime equivalent of DryIoc's ScopedTo<type> #827

@Geminior

Description

@Geminior

Certain other DI containers provide the notion of a scope that is bound to a specific type instance, such that when the instance is created, all dependencies are resolved in the scope of that instance (provided the dependencies where registered with this type of scoped lifetime).

In some scenarios, a type acts as a natural scope in an application, and in such scenarios this type of scope is useful.

Grabbed and slightly modified from DryIoc docs:

    class Foo
    {
        public SubDependency Sub { get; }
        public Dependency Dep { get; }
        public Foo(SubDependency sub, Dependency dep)
        {
            Sub = sub;
            Dep = dep;
        }
    }

    class Dependency
    {
        public SubDependency Sub { get; }
        public Dependency(SubDependency sub)
        {
            Sub = sub;
        }
    }

    class SubDependency { }
        var container = new Container();

        // This is required to mark that `Foo` opens the scope
        container.Register<Foo>(setup: Setup.With(openResolutionScope: true));

        container.Register<Dependency>();
        container.Register<SubDependency>(Reuse.ScopedTo<Foo>());

        var foo1 = container.Resolve<Foo>();
        var foo2 = container.Resolve<Foo>();

        Assert.AreNotSame(foo1, foo2);
        Assert.AreSame(foo1.Sub, foo1.Dep.Sub);
        Assert.AreNotSame(foo1.Sub, foo2.Sub);

So the main feature here is that the container manages the scope associated with each Foo instance.
Typically you will want a reference to that specific scope, so that it can be disposed along side the instance it's associated with, or if that is not possible, create a scope explicitly and resolve the root from there, and dispose of both together (not the responsibility of the container).

Is there a way to achieve this behaviour in Simple Injector, and if not, would it perhaps be a meaningful addition?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions