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?
If you want an instance that lasts for the duration of a user request (that eg might hold details of the user), then use scoped. If you want a new instance every time the container is asked to provide one (a resource access request that needs disposing quickly for example), then use transient.
} IServiceCollection is the collection of the service descriptors. We can register our services in this collection with different lifestyles (Transient, scoped, singleton) IServiceProvider is the simple built-in container that is included in ASP.NET Core that supports constructor injection by default.
Resolve dependencies using IServiceProvider You can use the IServiceCollection interface to create a dependency injection container. Once the container has been created, the IServiceCollection instance is composed into an IServiceProvider instance. You can use this instance to resolve services.
Scrutor is a supporting library for Microsoft. Extensions. DependencyInjection, it allows to register collections of types in our DI container. Here, I want to propose you one of strategies that you can use when it comes to types registration in your application.
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://docs.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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With