Home > Mobile >  Microsoft.Extensions.DependencyInjection auto resolve objects dependencies
Microsoft.Extensions.DependencyInjection auto resolve objects dependencies

Time:04-20

Previously I was using Unity for dependency injection, and it automatically resolved dependency's for me that code looked something like this:

IUnityContainer UnityContainer = new UnityContainer();
UnityContainer.RegisterType<IDataProvider, DataProvider>();

Some class to have IDataProvider injected into:

public class SomeClass
{
    private IDataProvider dataProvider;
    public SomeClass(IDataProvider dataProvider)
    {
         this.dataProvider = dataProvider;
    }
}

To resolve the dependencies for this object with unity I could simply type

SomeClass myClass = Unity.Resolve<SomeClass>();

And it would automatically try to inject the required constructor parameters from its ServiceCollection. Due to Unity being depreciated now, I've been trying to make the switch to Microsoft.Extensions.DependencyInjection, I've got the IServiceProvider setup and can return requested services, however I'm yet to figure out how to use this library (and if I need extra librarys for this functionality) top achieve the same result.

CodePudding user response:

This is a feature that is not supported by MS.DI and it contains no hooks that would allow you add this feature on top of MS.DI. If you choose to stick with MS.DI, you will have to register SomeClass in the container, either explicitly or using Auto-Registration; there's no way around this.

Explicit registrations means that you have a line of code for each class that you want to register, e.g.:

services.AddTransient<SomeClass>();

With Auto-Registration on the other hand, you apply Convention over Configuration and use Reflection to find types at runtime. For instance:

var types =
    from type in typeof(SomeClass).Assembly.GetTypes()
    // Define your convention here
    where typeof(ISomeInterface).IsAssignableFrom(type)
    where ...
    select type;

foreach (Type type in types)
{
    services.AddTransient(type, type);
}

Auto-Registration scales much better than the Explicit Register approach. This does require, however, some sort of convention that can be distilled out of the classes you wish to register using Reflection.

  • Related