在下面的代码示例中,Debug.Assert 将失败。
如果从 IBreaker 注册中删除 AsImplementedInterfaces() 扩展,则 foo.Bar 不会为空。为什么会这样?
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> {}
}