Inject already resolved instance (via constructor) in the same scope with Autofac?

Inject already resolved instance (via constructor) in the same scope with Autofac?

autofac resolve
autofac register class with constructor parameters
autofac constructor injection
autofac register generic
autofac resolve all implementations of interface
autofac module
autofac lifetime scope
autofac best practices

Well I think this is possible but not sure how it could be done. Here is my scenario: I have 2 services, one depends on another, like this:

public interface IServiceA {
    //...
}
public interface IServiceB {
    //...
}
//the actual implementation
public class ServiceA : IServiceA {
    //...
}
public class ServiceB : IServiceB {
    readonly IServiceA _serviceA;
    public ServiceB(IServiceA serviceA){
        _serviceA = serviceA;
    }
}

I have another class consuming both services like this:

public class MyConsumer {
    readonly IServiceA _serviceA;
    readonly IServiceB _serviceB;
    public MyConsumer(IServiceA serviceA, IServiceB serviceB){
        _serviceA = serviceA;
        _serviceB = serviceB;
    }
}

So here I would like the serviceB to be injected with what resolved for the serviceA right here in this constructor of MyConsumer. (meaning the serviceA injected into ServiceB should be exactly the instance serviceA injected into MyConsumer - not some new different instance). Note that: I don't want to expose ServiceA via ServiceB and just make MyConsumer depend on IServiceB only (actually ServiceA is the basic service while other services including ServiceB are just extensions, meaning there may be more services like ServiceB in this case)

I'm really new to Autofac and really even with Unity (I've used the most) I've never thought of this scenario before, so really I don't have any code made so far.

I hope someone here has encountered this same scenario before and could provide with me some suggestion, thanks!

Bonus question: what if the order of parameters (passed-in MyConsumer constructor) is changed? I mean does that affect the resolving order and can cause unexpected result? If possible the parameters order should not matter (because the MyConsumer should just care about what it need, not how the things it need are ordered).

A larger picture of the problem: Some ones have suggested to use defined scope which is supported by autofac for some cases. However my scenario here is different and I think that it's not very convenient to force autofac to understand what I want.

The MyConsumer here may actually never be resolved directly (using .Resolve method) because it may be just a dependency of another class (which is what we call .Resolve for). By using scope convention, I think it's the right approach but the scope in my case is different, I think it's naturally defined by the class's constructor (all dependencies injected in should be in the same scope - and each instance of a type in that scope should be a singleton - which is shared among them). Not sure why this is missing from what Autofac can provide us.


Here's a separate solution from the other answer that hopefully addresses your concerns about special usage of the container:

namespace AutofacTest
{
    public interface IServiceA { }
    public interface IServiceB { }

    public class ServiceA : IServiceA
    {
    }

    public class ServiceB : IServiceB
    {
        private readonly IServiceA _serviceA;

        public ServiceB (IServiceA serviceA)
        {
            _serviceA = serviceA;
        }
    }

    public class MyConsumer
    {
        private readonly IServiceA _serviceA;
        private readonly IServiceB _serviceB;

        public MyConsumer(Func<IServiceA> serviceAFactory, Func<IServiceA, IServiceB> serviceBFactory)
        {
            _serviceA = serviceAFactory();
            _serviceB = serviceBFactory(_serviceA);
        }
    }
}

In this solution I'm injecting factories instead of instances and then invoking them to get the instances. One thing that's a little bit ugly about this implementation is that parameter order now DOES matter.

If you really don't want the order to matter, you could expose a setter for the IServiceA on the IServiceB interface and then replace the constructor with something like

public MyConsumer(Func<IServiceA> serviceAFactory, Func<IServiceB> serviceBFactory)
{
    _serviceA = serviceAFactory();
    _serviceB = serviceBFactory(_serviceA);
    _serviceB.SetServiceA(_serviceA);
}

Registration Concepts, Components can be created via reflection (by registering a specific .NET type or open Build(); // Now you can resolve services using Autofac. For example  Autofac is a well-known and frequently used dependency injection framework for the .NET platform. We also refactor an existing program to make use of Autofac in a sample application. Dependency Injection in C# using Autofac - YouTube. Claudio Bernasconi. 884 subscribers. If playback doesn't begin shortly, try restarting your device.


I put together a small sample of what I think would work for your situation:

namespace AutofacTest
{
    public interface IServiceA { }
    public interface IServiceB { }
    public interface IMyConsumer { }

    public class ServiceA : IServiceA
    {
    }

    public class ServiceB : IServiceB
    {
        private readonly IServiceA _serviceA;

        public ServiceB (IServiceA serviceA)
        {
            _serviceA = serviceA;
        }
    }

    public class MyConsumer : IMyConsumer
    {
        private readonly IServiceA _serviceA;
        private readonly IServiceB _serviceB;

        public MyConsumer(IServiceA serviceA, IServiceB serviceB)
        {
            _serviceA = serviceA;
            _serviceB = serviceB;
        }
    }

    public class AutofacInit
    {
        public IContainer BuildContainer()
        {
            var containerBuilder = new ContainerBuilder();

            containerBuilder.RegisterType<ServiceA>().AsImplementedInterfaces().InstancePerLifetimeScope();
            containerBuilder.RegisterType<ServiceB>().AsImplementedInterfaces().InstancePerLifetimeScope();
            containerBuilder.RegisterType<MyConsumer>().AsImplementedInterfaces().InstancePerLifetimeScope();

            return containerBuilder.Build();
        }

        public void Test()
        {
            using (var container = BuildContainer())
            {
                using (var myConsumer = container.Resolve<Owned<IMyConsumer>>())
                {
                    //use myConsumer.Value
                }
            }
        }
    }
}

I am using nested lifetime scopes (created by resolving an Owned<IMyConsumer>) in which only one instance of IServiceA, IServiceB, and IMyConsumer will exist. One thing to note is that you should always be resolving/injecting an Owned<IMyConsumer> and never be resolving/injecting a plain IMyConsumer if you take this approach, otherwise the IServiceA and IServiceB dependencies will be singletons.

This should also handle your bonus question -- nothing in this sample cares about ordering of parameters.

Resolving Services, It is recommended you always resolve components from a lifetime scope where possible to make sure service instances are properly disposed and garbage  Autofac is an open-source dependency injection (DI) or inversion of control (IoC) container developed on Google Code. Autofac differs from many related technologies in that it sticks as close to bare-metal C# programming as possible. It is designed around the premise that it is wasteful to work in such a powerful language as C# but to lose that


To me it looks like all you need to do is to ensure that all of them - MyConsumer, ServiceA and ServiceB (and other "extensions" as you call them) - are registered as InstancePerLifetimeScope(). As long as they are resolved from the same scope all of them will be "singletons" for that scope. Have you tried it in your code? If you're having some problem with this approach then you need to explicitly say it in your question because it is pretty hard to figure out what your real problem is. Personally I think that the problem is not the autofac itself or fitting your services in it, it's just lack of familiarity with the new DI container - which is quite natural thing, every new technology has its learning curve. Just keep trying, keep experimenting, and you'll get it done. Autofac is very powerful DI container, so I'm pretty sure it can do what you want.

Dependency injection, Autofac gives us all the advantages that I mentioned in the previous article. One condition must be such that the class we register is in the same project, that is, the class gameServer = scope.Resolve(); }. And everything is already working :) SingleInstance() we can not do this via the InstancePerDependency​() object. Instance scope determines how an instance is shared between requests for the same service. Note that you should be familiar with the concept of lifetime scopes to better understand what’s happening here. When a request is made for a service, Autofac can return a single instance (single instance scope), a new instance (per dependency scope


Dependency Injection with Autofac, Using the Autofac dependency injection container to simplify the If you're already using a DI container and want to get a feel for how Autofac is Like MemoChecker , this class accepts its dependencies through its constructor. Requests from the same scope object will retrieve the same instance, while  Registration Concepts¶. You register components with Autofac by creating a ContainerBuilder and informing the builder which components expose which services.. Components can be created via reflection (by registering a specific .NET type or open generic); by providing a ready-made instance (an instance of an object you created); or via lambda expression (an anonymous function that executes to


Chapter 13. Autofac, In this chapter, we'll do the same with the Autofac DI CONTAINER. With Autofac​, we first create and configure a ContainerBuilder instance. where all components follow proper DI patterns such as CONSTRUCTOR INJECTION. scenario and see how we can resolve objects using an Autofac container. sign in now  Usage Note In Visual Basic and C#, you can call this method as an instance method on any object of type ContainerBuilder . any Controller which you've registered will be resolved via Autofac, not Activator. e. •Use the lifetime scope to resolve instances of the components. Read the Docs. Mvc.


Autofac multiple constructors, To create an instance of the factory, target type is got from the custom header When Autofac is resolving a dependency, it looks at the constructor of Mar 28, 2016 · Controllers are very easy to inject dependencies into, and a A constructor will have exact same name as the class and it does not have  Implicit Relationship Types¶. Autofac supports automatically resolving particular types implicitly to support special relationships between components and services.To take advantage of these relationships, simply register your components as normal, but change the constructor parameter in the consuming component or the type being resolved in the Resolve() call so it takes in the specified