Gabriel S. Gabriel S. - 1 month ago 8
C# Question

Postponing registration of property using Autofac

I'm trying to achieve the following dependency injection scenario using Autofac.

Suppose I have three classes, A, B and P. Class A holds a property of type P and also has a reference to B, which needs to be injected at runtime.

class A
{
private B _b;

public P Prop { get; set; }

InitializeProp()
{ ... }
}


At the same time, class B depends on a instance of P:

class B
{
private P _p;
}


Now, the most important detail: I need to somehow inject into B an instance of P. However, that instance must be Prop from class A, which is initialized only after InitializeProp() in A has been called. Assume InitializeProp() can be called later in the object's life time than the constructor of A.

Is this scenario achievable with Autofac?

I tried doing something like this but I get a circular reference exception, presumably when B is resolved further on:

containerBuilder.RegisterType<A>().SingleInstance();

containerBuilder.Register<Func<P>>(c =>
{
var a = c.Resolve<A>();
return () => a.Prop;
});

Answer

So eventually I figured it out, turns out Autofac is smarter than i thought.

It wasn't necessary to explicitly register a Func of P, but instead have this simplified registration:

builder.RegisterType<A>().SingleInstance();

builder.Register(c =>
{
  var a = c.Resolve<A>();
  return a.Property;
});

builder.RegisterType<B>();

Now in the main program i can do the following:

var a = container.Resolve<A>();
a.InitializeProperty();
a.Execute(); // calls B