Why would one use a third-party DI Container over the built-in ASP.NET Core DI Container?
Asked Answered
B

4

63

As currently there is lack of documentation on DI topic - Dependency Injection. What are pros/cons of using built-in DI over existing solutions like (Ninject, Autofac, StructureMap)? And what are current limitations of default dependency injection (if any)?

Bluebonnet answered 6/6, 2015 at 10:1 Comment(2)
Are there dotnetcore based implementations for any of the standard DI containers (ninject etc.) as yet?Copaiba
@AbhijeetPatel by now, most (if not all) DI Containers are compatible with .NET Core and .NET Standard.Zoara
Z
66

For product development of any reasonably sized application that practice loose coupling and follows the SOLID principles, .NET Core's DI container (MS.DI) is unsuited, because:

  • It doesn't help you in verifying your configuration, making it really hard to diagnose problems that come from common misconfigurations. In a reasonably sized application, it's actually quite hard to spot these mistakes yourself. UPDATE: Version 3 of MS.DI now contains a feature called ValidateOnBuild, but the only thing it does is check whether all dependencies of all registrations can be satisfied.
  • It is impossible to apply Cross-Cutting Concerns using interceptors or decorators in a maintainable fashion. This makes maintaining any reasonably sized application more expensive. UPDATE: There are several third-party libraries that try to fill the gap, but due to limitations in MS.DI, they can't completely fill that gap (e.g. decorate open-generic registrations, ensure disposal of decorated instances, etc.)
  • Although MS.DI supports mapping of open-generic abstractions to open-generic implementations, its implementation is rather naive and is unable to work with generic types with type constraints, more complex generic type mappings, and variance.
  • It is impossible to make conditional/contextual registrations, in such way that registrations only get injected to a certain set of consumers, while using Auto-Wiring. e.g. when having two components Service1 and Service2 that both depend on ILogger, you might want to inject Service1 with NullLogger and Service2 with FileLogger, or you want Service1 to be injected with Logger<Service1> and Service2 with Logger<Service2>.

The main reason for those limitations to exist is because it's the goal of the built-in container to provide DI capabilities to especially the framework itself, while keeping its feature set to a minimum in the hope that more-mature DI containers would be able to integrate with it. In other words, it tries to act as an Least-Common Denominator (LCD). Because of its LCD function, it can never grow to a full-fledged DI Container that is practical for application development (not without breaking the promise of being an LCD).

If you start with a new and simple project, my advice is to apply Pure DI. This means you hand-wire components inside the Composition Root without using a container and without creating your own DI Container. Instead you resolve your types by plugging in your custom IControllerActivator. Later on, when features such as Auto-Wiring, Auto-Registration and Interception would improve maintainability of your Composition Root, switch to one of the established DI libraries that fits your requirements.

Zoara answered 6/6, 2015 at 11:24 Comment(11)
Still valid with ASP.NET Core 2.0?Cocky
@Legends. Yep. This answer still holds with .NET Core 2.0.Zoara
@Zoara : Any improvements with .net core 2.2 and 3-preview ?Metrify
@Metrify Nope! And you don't have to expect any progress in this area. Microsoft has painted itself in a corner with their container. Their DI Container will never evolve to a feature-rich DI Container.Zoara
Still valid with .NET 5.0?Zoara
Yep. This is still the case for .NET 5.0.Zoara
Note that it is actually doable to use decorators in a maintainable fashion.Hasan
@Timo, in chapter 15 of my book, I explain in detail why this is not the case. But here's a simple example: try to decorate a generic class that is registered as open-generic registration.Zoara
@Zoara I agree that open generics are problematic, because the built-in container does not like open generic registrations combined with implementation factories. I was not addressing open generics, but merely contradicting the popular belief that d̶e̶c̶o̶r̶a̶t̶o̶r̶s̶ ̶a̶r̶e̶ ̶i̶n̶f̶e̶a̶s̶i̶b̶l̶e̶ ̶w̶i̶t̶h̶ ̶t̶h̶e̶ ̶b̶u̶i̶l̶t̶-̶i̶n̶ ̶c̶o̶n̶t̶a̶i̶n̶e̶r̶. demo proves.Hasan
Still valid with .NET 6.0?Zoara
Yep. This is still the case for .NET 6.0.Zoara
C
23

Here it is explained :

  • Transient - A new instance is created every time
  • Scoped - A single instance is created inside the current scope. It is equivalent to Singleton in the current scope
  • Singleton - A single instance is created and it acts like a singleton
  • Instance - A specific instance is given all the time. You are responsible for its initial creation

Alpha version had this limitations :

  • It only supports constructor injection
  • It can only resolve types with one and only one public constructor
  • It doesn’t support advanced features (like per thread scope or auto discovery)

If you aren't writing really complicated product default DI container should be sufficient for you. In other cases you can try libraries you already mentioned that have advanced features.

My advice would be to start with the default one and change implementation when(if) you hit something you can't do with it.

Cloche answered 6/6, 2015 at 11:3 Comment(1)
Alpha version is no longer relevant.Baron
L
7

Additionally, can someone help me to understand what is the difference between these registrations?

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IService, Service>();
    services.AddScoped<IService, Service>();
    services.AddSingleton<IService, Service>();
    services.AddInstance(service);
}

https://stackoverflow.com/revisions/30681477/8

  • Transient - instantiated every time it is retrieved
  • Scoped - instantiated once per http request and will be available for the lifetime of the http request
  • Singleton - instantiated once and will be available for the entire lifetime of your application
  • Instance - equivalent to singleton except you provide the object instance instead of the framework creating the instance

Source: http://www.khalidabuhakmeh.com/asp-vnext-dependency-injection-lifecycles, http://dotnetliberty.com/index.php/2015/10/15/asp-net-5-mvc6-dependency-injection-in-6-steps/

To explain why it's called scoped a bit more, consider this code:

// app startup
var services = new ServiceCollection();
services.AddScoped<IService, Service>();
var startupServices = services.BuildServiceProvider();
// request init
var requestServices = statupServices.CreateScope().ServiceProvider;

So in ASP.NET HttpContext.RequestServices is created in a similar fashion to above where CreateScope is called at the beginning of the request. But it can be used in contexts outside of ASP.NET in which case scope can have a different meaning than per request.

Lurk answered 10/11, 2015 at 23:21 Comment(0)
G
6

To answer your first question: it seems that ASP.NET docs were updated and now clearly state what is each type of registration for:

ASP.NET services can be configured with the following lifetimes:

Transient

Transient lifetime services are created each time they are requested. This lifetime works best for lightweight, stateless service.

Scoped

Scoped lifetime services are created once per request.

Singleton

Singleton lifetime services are created the first time they are requested, and then every subsequent request will use the same instance. If your application requires singleton behavior, allowing the services container to manage the service’s lifetime is recommended instead of implementing the singleton design pattern and managing your object’s lifetime in the class yourself.

Instance [pre RTM only!]

You can choose to add an instance directly to the services container. If you do so, this instance will be used for all subsequent requests (this technique will create a Singleton-scoped instance). One key difference between Instance services and Singleton services is that the Instance service is created in ConfigureServices, while the Singleton service is lazy-loaded the first time it is requested.


Updated in RTM

Note that in Asp.Net Core RTM docs Instance was removed. Instance is basically the same thing as Singleton, but they had different initialization semantics (Singleton was lazy loaded). But now there is no AddInstance API, only AddSignleton which can take already created instance.

Gery answered 14/2, 2016 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.