-
Notifications
You must be signed in to change notification settings - Fork 316
Add support for binding to factory #64
Comments
Instead of binding to an instance you can bind to a type. Then it'll get instantiated by DI along with injecting any dependencies. Do you have a specific example of where you need a factory? |
Yes, I have an example. See this pull request: https://github.com/aspnet/EndToEnd/pull/6 In Startup.cs
When I create the UserManager, I want to add a user to it (that's what CreateNewUserManager does):
If I would do something like:
there is no way of adding the user to the UserManager when the manager gets created. |
So this is not only about having a custom factory pattern, but this also about having an async factory pattern? That is, does the factory need to be able to do async work, such as database calls? |
Async would be nice but not necessary (at least initialy). If the function returns a task, the consumer could handle that. Maybe a GetServiceAsync later? :) I was talking to Suhas and he has another scenario where this would be very beneficial. He has a class that requires a HttpContext instance as constructor argument. He wants to inject that class into a controller constructor. However, the container does not have the HttpContext and thus cannot resolve his class instance. With support for Func we could resolve the current HttpContext when needed. Maybe @suhasj can post the actual code. |
That's not the way you do this particular scenario. Instead, you'd take an IContextAccessor in your class to get at the HttpContext |
It worked ! I was able to inject HttpContext using the IContextAccessor property |
Duplicate of #104 |
Feature proposal:
Today you can do:
But it would be nice to have an overload for AddInstance that accepts a Func and late binds that instance. Something like:
The instance is resolved when it is requested for the first time.
A workaround is to bind bind to a factory object or Lazy but it would nicer to have this out of the box.
The text was updated successfully, but these errors were encountered: