Skip to content

Auto cross-wiring ASP.NET Core components #442

@dotnetjunkie

Description

@dotnetjunkie

The ASP.NET Core integration package for Simple Injector contains an CrossWire<T> extension method that allows adding a registration to Simple Injector that forwards the request to the built-in container.

This might potentially lead to having to do quite some cross-wirings, and when it comes to registrations of generic types (such as IStringLocalizer<T> as seen in this Stackoverflow question), the number of registrations might explode.

So I'm toying around with implementing an ResolveUnregisteredType event that allows falling back to the .NET Core configuration system when such registration is missing from Simple Injector.

It looks like this:

public static void EnableAutoCrossWiring(this Container container, IApplicationBuilder builder)
{
    container.ResolveUnregisteredType += (s, e) =>
    {
        // Skip IEnumerable<T> registrations: they behave rather different in .NET Core, and
        // auto-wiring them would cause us to loose the possibility to tell the user he forgot
        // to register his collection.
        if (IsEnumerable(e.UnregisteredServiceType)) return;

        IServiceCollection services = GetCrossWireContext(container).Services;

        // Locate the ServiceDescriptor for the service type in .NET Core's IServiceCollection
        ServiceDescriptor descriptor = FindDescriptor(e.UnregisteredServiceType, services);

        // If such descriptor exists, we will cross-wire. If not, we skip this registration and 
        // Simple Injector will throw an exception.
        if (descriptor != null)
        {
            // Build a registration with the correct lifestyle based on information from .NET Core
            var registration = CreateRegistration(container, e.UnregisteredServiceType, builder);

            // Apply the registration to Simple Injector
            e.Register(registration);
        }
    };
}

What do you think? Should we add such feature? What could be the risks of doing this?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions