问题描述
我对 autofac 很陌生,所以我可能完全误用了它.
I'm very new to autofac so it's possible that I'm completely misusing it.
假设我有一个具有这种结构的类:
Let's say I have a class that has this structure:
public class HelperClass : IHelperClass
{
public HelperClass(string a, string b)
{
this.A = a;
this.B = b;
}
}
并且我有两个使用该类的类,但是构造函数需要不同的默认值.第二个构造函数仅用于测试目的——我们总是希望在真实"应用程序中有一个 HelperClass.:
and I have two classes that use that class, but require different defaults for the constructor. The second constructor is JUST for testing purposes -- we will always want a HelperClass in the "real" app.:
public class DoesSomething: IDoesSomething
{
public DoesSomething()
: this(new HelperClass("do", "something"));
{
}
internal DoesSomething(IHelperClass helper)
{
this.Helper = helper;
}
}
public class DoesSomethingElse : IDoesSomethingElse
{
public DoesSomethingElse()
: this(new HelperClass("does", "somethingelse"));
{
}
internal DoesSomethingElse(IHelperClass helper)
{
this.Helper = helper;
}
}
这是我的 AutoFac 模块:
Here's my AutoFac module:
public class SomethingModule: Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<DoesSomething>().As<IDoesSomething>();
builder.RegisterType<DoesSomethingElse>().As<IDoesSomethingElse();
}
}
我的问题:
- 当我对DoesSomething 或DoesSomethignElse 调用resolve 时——它会解析内部构造函数而不是公共构造函数吗?我需要让 IHelperClass 保持未注册状态吗?
- 如果是,我如何让它根据 IHelperClass 是在DoesSomething 还是DoesSomethingElse 中使用,向每个IHelperClass 实例传递不同的参数?
推荐答案
Autofac 不使用非公共构造函数.默认情况下,它只找到公共的,根本看不到其他的.除非您使用 .FindConstructorsWith(BindingFlags.NonPublic)
,否则它只会看到公共构造函数.因此,您的场景应该按照您的预期工作.
Autofac does not use non-public constructors. By default, it only finds public ones and simply doesn't see the others. Unless you use .FindConstructorsWith(BindingFlags.NonPublic)
, it will see only public constructors. Therefore your scenario should work as you expect it to do.
这篇关于使用 Autofac 将参数传递给构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!