7

I'm porting a project from .NET 4.52 to .NET Core. This project has previously used Structuremap for dependency injection and in structuremap you don't need to configure concrete types to enable dependency injection. Is there any way to do this with the built in dependency injection in .NET Core?

  • 1
    You can still use structure map if you want. http://andrewlock.net/getting-started-with-structuremap-in-asp-net-core/ – mbudnik Sep 30 '16 at 11:55
  • 1
    yes, but i'd like to go as native as possible and this seems like something they should have added or do you know for sure it's not possible? – Andreas Ljungström Sep 30 '16 at 12:14
  • Sticking to the Core DI library [might not be a good idea](https://stackoverflow.com/a/30682214/264697). – Steven Sep 30 '16 at 12:21
  • What @Steven said, the native DI is not meant to be feature rich and replace other DI systems. It's meant to serve as a base where other DI libraries can be plugged in and have a nice and simple DI for smaller projects to start with w/o having to rely on 3rd party on it. As such there are no plans to add auto discovery (register all classes of certain type or direct resolve concrete types) or have interceptors/decorators which you need for more advanced / complex applications (i.e. decorating classes / interfaces with a logger or caching decorators) – Tseng Sep 30 '16 at 12:30
  • 1
    Thanks for your comments. Will be looking to reverting the code back to structuremap then :) – Andreas Ljungström Sep 30 '16 at 12:39

1 Answers1

2

If you are trying to resolve a concrete type and have its dependencies injected from the IoC container then the following extension function may be of use to you. This makes the assumption that all dependencies of the concrete type can be resolved through the container.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class ServiceProviderExtensions
    {
        public static TService AsSelf<TService>(this IServiceProvider serviceProvider, params object[] overrides)
        {
            return (TService)AsSelf(serviceProvider, typeof(TService), overrides);
        }
        public static object AsSelf(this IServiceProvider serviceProvider, Type serviceType, params object[] overrides)
        {
            // ref: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.activatorutilities.createinstance?view=dotnet-plat-ext-5.0#definition
            // ref: https://github.com/dotnet/runtime/blob/main/src/libraries/Microsoft.Extensions.DependencyInjection.Abstractions/src/ActivatorUtilities.cs#L108-L118

            return ActivatorUtilities.CreateInstance(serviceProvider, serviceType, overrides);
        }
    }
}
Matt M
  • 592
  • 1
  • 5
  • 27