Why does AutoFac AsImplementedInterfaces break my resolver into another type?

In the following code example, Debug.Assert will fail.

If the AsImplementedInterfaces () extension is removed from the IBreaker registration, foo.Bar will not be null. Why is this so?

using System;
using System.Diagnostics;
using System.Reflection;
using Autofac;

namespace AutoFacTest
{
class Program
{
    static void Main(string[] args)
    {
        var builder = new ContainerBuilder();

        var thisAssembly = Assembly.GetExecutingAssembly();

        builder.RegisterAssemblyTypes(typeof(IFoo<>).Assembly, thisAssembly).AsClosedTypesOf(typeof(IFoo<>))
                .AsImplementedInterfaces().PropertiesAutowired().InstancePerDependency();

        builder.RegisterAssemblyTypes(typeof(IBar<>).Assembly, thisAssembly)
               .AsClosedTypesOf(typeof(IBar<>)).AsImplementedInterfaces().InstancePerDependency();

        builder.RegisterAssemblyTypes(typeof(IBreaker).Assembly, thisAssembly).InstancePerDependency()
                .AsImplementedInterfaces(); //<------ will work if this is removed

        var container = builder.Build();

        var foo = container.Resolve<IFoo<int>>();

        Debug.Assert(foo.Bar!=null);

        Console.ReadLine();
    }
}

public interface IBreaker {}

public class BreakerImpl<T> : IBreaker {}

public class BarImpl : IBar<int>{}

public class FooImpl : IFoo<int>
{
    public IBar<int> Bar { get; set; }
}

public interface IFoo<T>
{
    IBar<T> Bar { get; set; }
}

public abstract class Foo<T> : IFoo<T>
{
    public IBar<T> Bar { get; set; }
}

public interface IBar<T>{}

public abstract class Bar<T> : IBar<T> {}
}
+3
source share
2 answers

There are several problems with your registration. First of all, understand how it works RegisterAssemblyTypes: it takes an assembly and detects all the classes in that assembly and registers types with your builder. You can further increase the call by using AsXYZto control how each type is entered into the destination container.

, , , . . , , .

, Where, , .

+9

, IFoo IBar. AsImplmentedInterfaces(), .

, 2 .

builder.RegisterAssemblyTypes(typeof(IBreaker).Assembly, thisAssembly)
            .InstancePerDependency()
            .AsClosedTypesOf<IBreaker>()
            .AsImplementedInterfaces();

, " " .

builder.RegisterAssemblyTypes(typeof(IBreaker).Assembly, thisAssembly)
            .InstancePerDependency()
            .Except<IFoo>().Except<IBar>() //Not sure if you have to specify the concrete types or if the interfaces are fine
            .AsImplementedInterfaces();
0

All Articles