Dependency injection in .NET Core

5

I am migrating a WebAPI project with .NET Framework 4.6 for .NET Core.

In my project I use Unity to do Dependency Injection:

var container = new UnityContainer();
DependencyResolver = new UnityDependencyResolver(container);
container.RegisterType<IUserService, UserService>();

In the .NET Core I was not able to use Unity the same way I did in .NET 4.6 and found a solution to use that way by putting it in my Startup.cs

// DI Containers Registration
services.AddTransient<IUserService, UserService>();

What would be the best practice today in .NET Core for Dependency Injection, it's worth using some component like StructureMap, CastleWindsor.

    
asked by anonymous 03.11.2017 / 22:09

1 answer

1

After research I found some interesting material, here are some examples:

We can inject dependency in .NET Core as follows:

public void ConfigureServices(IServiceCollection services)
{    
    services.AddMvc();

    services.AddSingleton<IRenderSingleton, RenderSingleton>();

    services.AddScoped<IRenderScoped, RenderScoped>();

    services.AddTransient<IRenderTransient, RenderTransient>();    
}

In this code example there are 3 life cycle types that can be used:

  • Singleton (which gives me a single reference of this class in the life cycle of an application),
  • Transient (it will always generate a new instance for every item found that has such a dependency, ie if there are 5 dependencies it will be 5 different instances) and
  • Scoped (this is different from Transient that guarantees that in a request an instance of a class is created where there are other dependencies, this single instance is used for all, renewing only on subsequent requests, but compulsory).
22.01.2018 / 09:30