Dependency Injection in . NET Core

Asked

Viewed 1,032 times

5

I am migrating a Webapi project with . NET Framework 4.6 to . NET Core.

In this my project I use Unity to do Dependency Injection:

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

No . NET Core couldn’t use Unity the way I did in . NET 4.6 and found a solution to use this way, putting 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 is worth using some component like Structuremap, Castlewindsor.

1 answer

2


After researches I found an interesting material, following examples:

We can inject dependency into . 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 have 3 life cycle types that can be used:

  • Singleton (that guarantees me a single reference of this class in the life cycle of an application),
  • Transient (will always generate a new instance for each found item that has such a dependency, that is, if there are 5 dependencies there will be 5 different instances) and
  • Scoped(different from Transient that ensures that in a request an instance of a class is created where if there are other dependencies, use this single instance for all, renewing only in subsequent requests, but, maintaining this obligation).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.