Skip to content

Passing additional arguments to service resolution #36058

@NinoFloris

Description

@NinoFloris

I'd like to see support in the container for extra arguments being passed that aren't registered services. Quite like ObjectFactory (from ActivatorUtilities).

These arguments would be passed in via a new IServiceProvider method (we have DIM, let's use it).

object GetService(Type t, params object[] additionalArguments)

Another option could be to pass them during IServiceScopeFactory.CreateScope(args) constraining the feature in exchange for more resolution regularity.

The addition would open up a canonical way to create scoped/transient services that need arguments coming from the request or other pipeline-like data (as I have use for it outside ASP.NET Core too). The container would be able to manage the lifetime of such services (especially scoped) like any other.

These additional arguments would be available for consumption in the implementationFactory. If dependencies of this service need some or all of these extra arguments, nested calls to IServiceProvider.GetService(ty, args) would allow for this. I'm not sure if it would make sense to support full auto-wiring, meaning implementationType and constructor selection by the container, it could get messy quickly.

Example:

AddService<IFoo,Foo>((sp, args) => new Foo(sp.GetService<Bar>(args[1]), args[0])); 

ASP.NET Core could build on top of this functionality and finally add support for services that need HttpContext or parts of it (User is extremely common). Service registration would be extended with an extension method like AddHttpContextService and middleware and controller resolution would pass the extra argument for specifically these services.

Passing these arguments during scope creation instead would also simplify resolution here.

This would allow most uses of IHttpContextAccessor to be replaced by something conceptually cleaner and more performant. Today hacks like IUserAccessor or scoped holder objects that expose a Create method need to be used to work around the lack of proper framework support.

This area really just needs some love, it could be much better.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions