Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get container type in AutoFac

For example, I have registered class C1 with one parameter in constructor of type System.Type. I have another class (C2) with injected parameter of type C1. And I want receive typeof(C2) automatically in C1 constructor. Is it possible in some way?

Example code:

public class C1
{
  public C1(Type type) {}

  // ...
}

public class C2
{
  public C2(C1 c1) {}

  // ...
}

// Registration
containerBuilder.Register(???);
containerBuilder.Register<C2>();
like image 660
oryol Avatar asked Jan 23 '11 14:01

oryol


People also ask

What is Autofac container?

AutoFac is an Inversion of Control container that resolves dependencies of an application. This means that it also is a dependency injection framework.

Does Autofac use reflection?

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 .

How does Autofac choose a constructor?

Autofac's default implementation of this interface ( MostParametersConstructorSelector ) chooses the constructor with the most parameters that are able to be obtained from the container at the time of resolve.


1 Answers

This should do it:

builder.RegisterType<C1>();
builder.RegisterType<C2>();
builder.RegisterModule(new ExposeRequestorTypeModule());

Where:

class ExposeRequestorTypeModule : Autofac.Module
{
    Parameter _exposeRequestorTypeParameter = new ResolvedParameter(
       (pi, c) => c.IsRegistered(pi.ParameterType),
       (pi, c) => c.Resolve(
           pi.ParameterType,
           TypedParameter.From(pi.Member.DeclaringType)));

    protected override void AttachToComponentRegistration(
            IComponentRegistry registry,
            IComponentRegistration registration)
    {
        registration.Preparing += (s, e) => {
            e.Parameters = new[] { _exposeRequestorTypeParameter }
                .Concat(e.Parameters);
        };
    }
}

Any component that takes a System.Type parameter will get the type of the requestor passed to it (if any.) A possible improvement might be to use a NamedParameter rather than TypedParameter to restrict the Type parameters that will be matched to only those with a certain name.

Please let me know if this works, others have asked about the same general task and this would be good to share with them.

like image 121
Nicholas Blumhardt Avatar answered Sep 22 '22 14:09

Nicholas Blumhardt