How to handle circular links with Autofac 2.4.5?

The autofac wiki page on Circular Links says to use:

cb.Register<DependsByProp>().OnActivated(ActivatedHandler.InjectUnsetProperties);

But it looks like the ActivatedHandler no longer exists in 2.4.5. Digging in the source, I found an implementation of this class, so I included the implementation of the method in OnActivated. Unfortunately, this still does not work.

I have compiled a minimal registry that looks like the one on the wiki page.

class M
{
    public VM VM { get; set; }

    public M()
    {
    }
}

class VM
{
    public VM(M m)
    {
    }
}

[Fact]
void CanResolveCircular()
{
    ContainerBuilder builder = new ContainerBuilder();

    builder.RegisterType<VM>();
    builder.RegisterType<M>().OnActivated(e => e.Context.InjectUnsetProperties(e.Instance));

    using (var container = builder.Build())
    {
        var m = container.Resolve<M>();
        Assert.NotNull(m);
    }
}

This code still throws an exception when trying to resolve. What am I missing? What is the right way to get Autofac to handle circular dependencies?

+5
source share
2 answers

Autofac :

, , Factory.

M VM InstancePerDependency ( FactoryScope), . M VM.

, , VM, M, , M , InstancePerDependency (, SingleInstance). :

builder.RegisterType<M>().PropertiesAutowired(true).SingleInstance();

. PropertiesAutowired (true). OnActivated .

M , LifetimeScope InstancePerLifetimeScope.

+7

, , :

class DependsByProp1
{
    public DependsByProp2 Dependency { get; set; }
}

class DependsByProp2
{
    public DependsByProp1 Dependency { get; set; }
}

// ...

var cb = new ContainerBuilder();
cb.RegisterType<DependsByProp1>()
      .InstancePerLifetimeScope()
      .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
cb.RegisterType<DependsByProp2>()
      .InstancePerLifetimeScope()
      .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);

/

+5

All Articles