假设我有以下类及其接口
public class MyService : IMyService
{
int _value;
public MyService (int value)
{
_value = value;
}
}
public class MyClass : IMyClass
{
IMyService _myService;
public MyClass(IMyService myService)
{
_myService = myService;
}
}
步骤1:使用Autofac在测试项目中设置构造函数:
public class Configuration : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<MyClass>().As<IMyClass>()
.InstancePerLifetimeScope();
builder.RegisterType<MyService>().As<IMyService>()
.InstancePerLifetimeScope();
}
}
步骤2:设置测试
public class MyApplication
{
readonly int _value = 1234;
private MyClass _myClass;
public MyApplication(IMyClass myClass)
{
_myClass = myClass;
}
}
现在,我如何注入配置器未知但“MyApplication”已知的参数“value”?
在我想要这么做之前
public class MyApplication
{
readonly int _value = 1234;
private MyClass _myClass;
public MyApplication()
{
_myService = new MyService(_value);
_myClass = new MyClass(_myService);
}
}
但是现在我正在尝试我们依赖反转和依赖注入,最终出现了上面描述的问题。
您必须在autofac配置中调用构造函数。
builder.Register((comCont, parameters) => new MyClass(123))
.As<IMyClass>()
.InstancePerLifetimeScope();