假设我有以下几点:
public class Test
{
public IDependency Dependency { get; set; }
}
IDependency
和Test
登记在我的Autofac建设者。我IDependency
解析工作正常,但我想要实现的是能够在代码返回Test
的新实例(例如return new Test();
),并有它由Autofac预填充IDependency
性能。
我已经试过在我的容器:
builder.Register(x => new Test {
x.Resolve<IDependency>()
});
然而,每次我在代码new Test()
,它的IDependency
属性是null
。那可能吗?
(仅供参考,我的思路导致了这次尝试的是,我最初并构造注射Test
但后来意识到,在某些情况下,我需要手动构建new Test()
实例代码,并不能找出放什么,以满足构造函数签名的public Test(IDependency dependency)
,仍然有Autofac解决依赖性)
只是一个想法 - 你说你需要一些机制,在你的代码来构建Test
对象的新实例(与它的依赖注入)编程?
有内置到Autofac获得工厂的注册类型方便的功能。我建议你切换到构造器注入:
public class Test
{
public Test(IDependency dependency)
{
Dependency = dependency;
}
public IDependency Dependency { get; }
}
然后用Autofac作为注册类型:
cb.ResisterType<MyDependency>().As<IDependency>();
cb.RegisterType<Test>();
然后,所有你需要做的无论你想手动构建测试的一个新实例()是在你的构造要求Func<Test>
。 Autofac会生成一个工厂让你只要你喜欢instansiate Test类......但没有紧耦合到Autofac库:
public class SomeAppLogic
{
public SomeAppLogic(Func<Test> testFactory)
{
// Some app logic
for (int i = 0; i < 10; i++)
{
// Invoke the testFactory to obtain a new instance
// of a Test class from the IoC container
Test newTestInstance = testFactory.Invoke();
}
}
}
Autofac称此为“动态实例”,这是这里介绍:https://autofaccn.readthedocs.io/en/latest/resolve/relationships.html#dynamic-instantiation-func-b