我在使用 Autofac(版本 3.0.2)的 Funcs 分辨率时遇到问题。为什么 Autofac 能够为它无法解析的类型返回 Funcs?似乎 Autofac 在执行 func 时进行依赖解析,这似乎不正确,应该在创建 Func 时完成(不创建Foo
类型,但确保可以使用已知的注册类型调用其构造函数)。
using System;
using Autofac;
using NUnit.Framework;
namespace AutofacTest
{
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<Foo>().AsSelf().AsImplementedInterfaces();
var container = builder.Build();
//var foo = container.Resolve<IFoo>(); //Throws because the int arg can't be resolved (as it should)
Assert.True(container.IsRegistered<Func<int, IFoo>>()); //This is valid and makes sense
var fooFunc = container.Resolve<Func<int, IFoo>>();
var foo = fooFunc(9);
//Assert.False(container.IsRegistered<Func<string, IFoo>>()); //Why is this true?
var badFooFunc = container.Resolve<Func<string, IFoo>>(); // Why doesn't Autofac throw here?
var badFoo = badFooFunc(string.Empty); // Autofac throws here
}
}
interface IFoo { }
public class Foo : IFoo
{
public string ArgStr { get; set; }
public Foo(int arg)
{
this.ArgStr = arg.ToString();
}
}
}