LightInject icon indicating copy to clipboard operation
LightInject copied to clipboard

Using same instance in all sub-sequence cosntructors

Open Kurira opened this issue 9 years ago • 2 comments

I was looking on how to do it using life times, but couldn't find it (maybe I just don't the how this life time named). What I need is:

public class Root
{
    public Root(Child c, ChildWrap cw)
    {
    }
}

public class ChildWrap
{
    public ChildWrap(Child c)
    {
    }
}

That Register<Root>(); would use the same Child instance for root and ChildWrap in each new Root instance Child would be the same. Root.Child == Root.ChildWrap.Child => true. Is there a way of doing it with life times? I know I can use the factory to achieve that, but I have hundreds of classes which need that.

Kurira avatar Apr 28 '17 08:04 Kurira

There are two ways to achieve this. Either you can register the Child as a singeton service (PerContainerLifetime) or as a scoped service (PerScopeLifetime) where the latter will require a scope to be present. It all depens on the type of application you are building http://www.lightinject.net/#perscopelifetime

seesharper avatar Apr 28 '17 09:04 seesharper

Singleton wouldn't work because I need a new instance of child per every root and I don't really have a container to create in MVC application or PerScopeLifetime works correctly from MVC DI @seesharper?

Kurira avatar Apr 28 '17 17:04 Kurira