-
Notifications
You must be signed in to change notification settings - Fork 29
I dont' understand have functions with arguments works #57
-
I don't understand how func with arguments work
This example
.To<Func<int, IDependency>>(ctx => dependencyId => { // Builds up an instance of type Dependency // referring the source code statement "dependencyId" ctx.Inject<Dependency>(out var dependency); return dependency; })
I guess dependencyId is somehow wired to the int id argument to the constructor of Dependency class. But I want to understand how you'll achieve that if you have two int arguments for example.
My guess is that it should emit compile time error. In this case what are my options? To create the instance with new operator?
Beta Was this translation helpful? Give feedback.
All reactions
DI.Setup(nameof(Composition)) .Bind<IClock>().As(Lifetime.Singleton).To<Clock>() // Binds a dependency of type int // to the source code statement "dependencyId" .Bind<int>().To<int>("dependencyId") .Bind<Func<int, IDependency>>() .To<Func<int, IDependency>>(ctx => dependencyId => { // Builds up an instance of type Dependency // referring the source code statement "dependencyId" ctx.Inject<Dependency>(out var dependency); return dependency; }) .Bind<IService>().To<Service>() // Composition root .Root<IService>("Root");
The key here is .Bind<int>().To...
Replies: 1 comment 1 reply
-
DI.Setup(nameof(Composition)) .Bind<IClock>().As(Lifetime.Singleton).To<Clock>() // Binds a dependency of type int // to the source code statement "dependencyId" .Bind<int>().To<int>("dependencyId") .Bind<Func<int, IDependency>>() .To<Func<int, IDependency>>(ctx => dependencyId => { // Builds up an instance of type Dependency // referring the source code statement "dependencyId" ctx.Inject<Dependency>(out var dependency); return dependency; }) .Bind<IService>().To<Service>() // Composition root .Root<IService>("Root");
The key here is .Bind<int>().To<int>("dependencyId"). We're just declaring that if some type requires int, the code generator simply replaces the injection with the dependencyId string. And this will work fine inside the lambda declaration as passing an argument named dependencyId.
Note
Please see the generated code to understand the idea, it's pretty simple.
But .Bind<int>().To<int>("dependencyId") works just like a normal binding. So you can use tags if, for example, you have multiple instances of type int. I've updated the example and added another argument. I hope this helps.
Using a binding of the form .Bind<int>().To<int>("dependencyId") is a kind of hack that allows you to replace an injection with just its own string.
Beta Was this translation helpful? Give feedback.
All reactions
-
Thanks, I missed that line
.Bind().To("dependencyId")
Beta Was this translation helpful? Give feedback.