autofac scope around a resolved instance

2019-08-27 22:23发布

问题:

I'm somewhat new to autofac, but have already used it successfully with different "simple" configurations. Now I'm trying something more complex and struggle with working this out.

Essentially, I have an entry point where all autofac configuration is done and the first objects are resolved, which themselves get dependencies by constructor injection, their dependencies can have other dependencies and so on.

Some code:

public class Root
{
    public Root(A.Factory factory)
    {
        for (int i = 0; i < 3;i++)
        {
            A obj = factory();
            // do something here
        }
    }
}

public class A
{
    public delegate A Factory();

    public A(B b, C c)
    {
    }
}

public class B
{
    public B(C c)
    {
    }
}

public class C
{
}

What I want is: Class Root is resolved only once. Class A should be resolved as a new instance everytime. For each A and its children, , instances of B and C should be shared. I.e: "Inside" each A, there's only one instance of each B and C. But also each A has it's own instances of B and C.

I think I could potentially do this with Owned (haven't tried yet). Anyhow, I'd like to keep all autofac specific code out of my business classes, so I thought maybe there's a way to tell the registration that it should create a new scope each time an A is resolved.

Is this possible with autofac? Do I have strange requirements or do my thoughts go the wrong way? Is this even possible with other DI frameworks beside autofac?

Best regards,

Kc

Update 2018-08-07:

Maybe I wasn't clear enough about what I have in mind. I tried to make a picture of the structure I want to achieve:

Each of the letters represents a resolved instance of the corresponding class. The arrows show where these instances should be injected. So as you can see, each time i resolve an instance of A in the root instance, new instances of B and C are created. However, the same instance of C should be injected into those new A and B instances. This shouldn't be restricted to only two classes anyhow, so manual wiring should be kept at a minimum.

You can imagine A as a kind of scope generator for all dependencies that follow down the road.

In the meantime, I found out that Ninject has an extension for named scopes (Ninject.Extensions.NamedScope) that allows such things. The configuration would be somehow like this:

Bind<A>.ToSelf().DefinesNamedScope("ScopeA");
Bind<B>.ToSelf().InNamedScope("ScopeA");
Bind<C>.ToSelf().InNamedScope("ScopeA");

Is there something like this in autofac?