Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFac: What does PropertyWiringFlags.AllowCircularDependencies do?

I have part of a code that has dependencies that look as follows:

public class MyPage : Page //ASPX WebForms page
{
    public IPersonBl PersonBl { get; set; }

}

public class PersonBl : IPersonBl
{

    public PersonBl(ISomeMagicBl magicBl){...}

}

public class SomeMagicBl : ISomeMagicBl
{
    public IPersonBl PersonBl { get; set; }

    public SomeMagicBl(/*Other dependencies*/) {...}
}

My module configuration looks as follows

...
builder.RegisterAssemblyTypes(ThisAssembly).Where(t => t.Name.EndsWith("BL")).AsImplementedInterfaces().PropertiesAutowired(PropertyWiringFlags.AllowCircularDependencies).InstancePerLifetimeScope();
...

As can be seen, I have circular dependencies in my classes which I was able to resolve by using the ..PropertiesAutowired(PropertyWiringFlags.AllowCircularDependencies)...

My Question: What exactly does this flag do behind the scenes to solve these circular dependencies??

like image 815
Juri Avatar asked Oct 09 '22 11:10

Juri


2 Answers

The flag changes the point at which property injection is done for the type from construction time to after the rest of the graph has been created. It relies on one or more of the components in the cycle having some kind of sharing (singleton or per-request) - even with the flag, if all of the components are instance-per-dependency then a kind of cycle will still exist.

Without the flag, Autofac considers all of the dependencies of the component, properties or not, to be prerequisites to letting any other component get a reference to it. As a default this is more reliable.

like image 167
Nicholas Blumhardt Avatar answered Oct 13 '22 10:10

Nicholas Blumhardt


just for reference, another good way to resolve a circular dependency is by taking a dependency on Func<T>, as long as you don't access the func in the constructor.

like image 36
flq Avatar answered Oct 13 '22 10:10

flq