Reputation: 349
Assume that I have the following classes with their interfaces
public class MyService : IMyService
{
int _value;
public MyService (int value)
{
_value = value;
}
}
public class MyClass : IMyClass
{
IMyService _myService;
public MyClass(IMyService myService)
{
_myService = myService;
}
}
Step 1: Setting up a constructor inside my test project using autofac:
public class Configuration : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<MyClass>().As<IMyClass>()
.InstancePerLifetimeScope();
builder.RegisterType<MyService>().As<IMyService>()
.InstancePerLifetimeScope();
}
}
Step 2: Set up test
public class MyApplication
{
readonly int _value = 1234;
private MyClass _myClass;
public MyApplication(IMyClass myClass)
{
_myClass = myClass;
}
}
Now, how do I inject the parameter "value" which is unknown by the configurator but known by "MyApplication"?
Before the idea was to do this
public class MyApplication
{
readonly int _value = 1234;
private MyClass _myClass;
public MyApplication()
{
_myService = new MyService(_value);
_myClass = new MyClass(_myService);
}
}
But now I am trying to us dependency inversion and dependency injection ending up in the above described problem.
Upvotes: 1
Views: 83
Reputation: 62213
You have to call the constructor in the autofac configuration.
builder.Register((comCont, parameters) => new MyClass(123))
.As<IMyClass>()
.InstancePerLifetimeScope();
Upvotes: 2