hasrthur
hasrthur

Reputation: 1490

ASP.NET Core and injecting IServiceProvider

So, I've been reading about CQRS while deciding about architecture for my project and found this library. It's not very complex or anything like that but one thing caught my eye: here the ISeviceProvider is being injected and here it is being used. So, my question: is it a good practice to build objects with service provider directly, meaning without the injecting? If not which would be the correct way to build objects if the type of object will be known only in runtime?

Upvotes: 3

Views: 12425

Answers (2)

juunas
juunas

Reputation: 58733

Using IServiceProvider is basically the only option for DI (e.g. via RequestServices in MVC components) if you only know the type at run-time.

Constructor injection is only viable if you already know the type at compile-time, because you must specify the type of the object in the constructor.

Depending on the need, you can also register an implementation factory in ConfigureServices(), and give out different instances of some interface depending on runtime information.

EDIT: An example of an implementation factory in ASP.NET Core:

services.AddTransient<IDataService, DataService>((ctx) =>
{
    IOtherService svc = ctx.GetService<IOtherService>();
    //IOtherService svc = ctx.GetRequiredService<IOtherService>();
    return new DataService(svc);
});

Here DataService depends on IOtherService, so it gets it from the service provider with GetService<T>(). You can use GetRequiredService<T>() to enforce the requirement.

Upvotes: 3

Steven
Steven

Reputation: 172606

is it a good practice to build objects with service provider directly, meaning without the injecting?

It depends. Injecting a generic resolver into a class instead of specific dependencies is a pattern generally referred to as Service Locator and it is considered to be an anti-pattern.

Whether or not the use of this IServiceProvider is an implementation of the Service Locator anti-pattern however, depends on how it is used, as explained here:

A DI container encapsulated in a Composition Root is not a Service Locator - it's an infrastructure component.

We can consider this CommandProcessor to be a piece of infrastructure, as long as it is "encapsulated in a Composition Root".

Upvotes: 3

Related Questions