In a unit test I resolve an interface with sending arguments for its constructor as below:
var args = new { arg1 = "arg1 value", arg2 = "arg2 value" };
var component = container.Resolve<IMyDependency>(args);
and it works fine. But now I want to do it in constructor injection, for example in:
public class Foo
{
private IMyDependency _dep;
public Foo(IMyDependency dep) { _dep = dep; }
}
So, As a try I register it with UsingFactoyMethod()
like this:
public class BarInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<IMyDependency>().UsingFactoryMethod(
() =>
{
var args = new { arg1 = "arg1 value", arg2 = "arg2 value" };
var result = container.Resolve<IMyDependency>(args);
return result;
}).LifestyleTransient());
// + some other registerations and installs
}
}
But I have still error:
Can't create component 'namespace.MyDependency' as it has dependencies to be satisfied.
'namespace.MyDependency' is waiting for the following dependencies:
- Parameter 'arg1' which was not provided. Did you forget to set the dependency?
- Parameter 'arg2' which was not provided. Did you forget to set the dependency?
I think you should try register IMyDependency implementaion with it's constructor args instead of using "UsingFactoyMethod()":
string someArg = "something";
container.Register(
Component.For<IMyDependency>().ImplementedBy<MyDependencyImp>()
.DependsOn(Dependency.OnValue("someArg",someArg)).LifestyleTransient());
Assuming MyDependencyImp constructor looks something like this:
public MyDependencyImp(string someArg)
{
/....
}
More info here .
Do you register IMyDependency anywhere else? It's tough to say what's wrong until you post the actual code.
This should work:
container.Register(
Component.For<IMyDependency>().UsingFactoryMethod(
() =>
{
return new MyDependency("arg1 value", "arg2 value");
}).LifestyleTransient());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.