All Questions
Tagged with .net-core dependency-injection
1,177
questions
269
votes
4
answers
246k
views
.NET Core DI, ways of passing parameters to constructor
Having the following service constructor
public class Service : IService
{
public Service(IOtherService service1, IAnotherOne service2, string arg)
{
}
}
What are the choices of ...
192
votes
11
answers
191k
views
Unable to resolve ILogger from Microsoft.Extensions.Logging
I've configured my console application's Main like so
var services = new ServiceCollection()
.AddLogging(logging => logging.AddConsole())
.BuildServiceProvider();
And then I try to use it ...
126
votes
4
answers
104k
views
.NET Core IServiceScopeFactory.CreateScope() vs IServiceProvider.CreateScope() extension
My understanding is that when using the built in the dependency injection, a .NET Core console app will require you to create and manage all scopes yourself whereas a ASP.NET Core app will create and ...
121
votes
2
answers
20k
views
On IServiceProvider what are the differences between the GetRequiredService and GetService methods?
What are the differences between IServiceProvider.GetRequiredService() and IServiceProvider.GetService()?
When is it a better idea to use GetRequiredService()?
121
votes
7
answers
213k
views
How to get an instance of IServiceProvider in .NET Core?
IServiceProvider is an interface with single method:
object GetService(Type serviceType);
It's used to create instances of types registered in .NET Core native DI container.
An instance of ...
118
votes
6
answers
85k
views
Dependency Injection with classes other than a Controller class
At this point I'm injecting things into my Controllers with ease, in some cases building my own ResolverServices class. Life is good.
What I cannot figure out how to do is get the framework to ...
107
votes
5
answers
75k
views
Replace service registration in ASP.NET Core built-in DI container?
Let us consider a service registration in Startup.ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IFoo, FooA>();
}
Is it possible to ...
106
votes
1
answer
46k
views
When are .NET Core dependency injected instances disposed?
ASP.NET Core uses extension methods on IServiceCollection to set up dependency injection, then when a type is needed it uses the appropriate method to create a new instance:
AddTransient<T> - ...
93
votes
7
answers
99k
views
How can I pass a runtime parameter as part of the dependency resolution?
I need to be able to pass a connection string into some of my service implementations. I am doing this in the constructor. The connection string is configurable by user will be added the ...
74
votes
3
answers
84k
views
Proper way to register HostedService in ASP.NET Core. AddHostedService vs AddSingleton
What is the proper way to register a custom hosted service in ASP.NET Core 2.1? For example, I have a custom hosted service derived from BackgroundService named MyHostedService. How should I register ...
73
votes
6
answers
60k
views
Inject service into Action Filter
I am trying to inject a service into my action filter but I am not getting the required service injected in the constructor. Here is what I have:
public class EnsureUserLoggedIn : ...
72
votes
9
answers
32k
views
Does .net core dependency injection support Lazy<T>
I am trying to use the generic Lazy class to instantiate a costly class with .net core dependency injection extension. I have registered the IRepo type, but I'm not sure what the registration of the ...
62
votes
3
answers
65k
views
Unable to resolve service for type 'System.String' while attempting to activate 'MyService'
I'm seeing the following exception in my Service Fabric Stateless ASP.NET Core app.
System.InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate '...
61
votes
1
answer
26k
views
How to determine if service has already been added to IServiceCollection
I am creating helper classes to simplify configuration and injection of interfaces via IServiceCollection for a library. The libraries constructor contains a number of dependencies that are likely to ...
56
votes
6
answers
50k
views
Dependency Injection in .NET Core inside a class library
How can I inject one class into another inside a .NET Core library project?
Where should I configure DI as it is done in StartUp Class ConfigureServices in API project?
55
votes
2
answers
39k
views
Unit Testing IServiceCollection Registration
I'm trying to figure out the easiest way to test my Service Registrations method for my framework. I'm creating dynamic services my registration looks like so:
var messageHubConfig = new ...
48
votes
5
answers
77k
views
Using Factory Pattern with ASP.NET Core Dependency Injection
I need the ASP.Net Core dependency injection to pass some parameters to the constructor of my GlobalRepository class which implements the ICardPaymentRepository interface.
The parameters are for ...
43
votes
1
answer
18k
views
How is a Scoped service instance handled in a .NET Core Console application?
I copied this from ConfigureServices in a web application I'm building, where I'm trying to move away from the web and only use a console app or service:
serviceCollection.AddScoped<IDbConnection, ...
40
votes
5
answers
38k
views
Dependency injection in ASP.NET Core 2 throws exception
I receive following exception when I try to use custom DbContext in Configure method in Startup.cs file. I use ASP.NET Core in version 2.0.0-preview1-005977
Unhandled Exception: System.Exception: ...
39
votes
3
answers
59k
views
How to register dependency injection with generic types? (.net core)
I have an asp.net core web app with multiple parameters in appSettings.json file.
I didnt' want to have services having IOptions<MyObject> in the constructor.
I wanted MyObject in the ...
39
votes
1
answer
42k
views
Using Dependency Injection with .NET Core Class Library (.NET Standard)
I have gone through the link:
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/dependency-injection
and learnt that how I can use dependency injection for Web API.
As mentioned in ...
38
votes
4
answers
60k
views
Inject generic interface in .NET Core
I want to inject this interface to my controllers:
public interface IDatabaseService<T>
{
IEnumerable<T> GetList();
...
}
I want to use generic, because in my WebApi project i ...
38
votes
2
answers
20k
views
Pass ILogger or ILoggerFactory to constructors in AspNet Core?
The MS docs article "Introduction to Logging in ASP.NET Core" gives 2 examples of constructor injection
using ILogger
private readonly ILogger _logger;
public TodoController(ILogger<...
36
votes
3
answers
30k
views
ASP.NET Core Singleton instance vs Transient instance performance
In ASP.NET Core Dependency Injection, I just wonder if registering Singleton instances will improve performance instead of registering Transient instances or not?
In my thinking, for Singleton ...
35
votes
5
answers
12k
views
Base Class type for ILogger<T> using Dependency Injection
I have a base class that does some work, including logging. I have an ILogger dependency injected into the constructor
public abstract class BaseClassExample
{
protected readonly ILogger<...
29
votes
1
answer
35k
views
How to get an instance of IConfiguration in asp.net core?
I making a unittesting project to test my webapi and i need to initialize a controller the problem is that in the constructor it receive a IConfiguration that it is provide by dependency-injection and ...
29
votes
2
answers
35k
views
Unable to resolve service for type Microsoft Extensions Configuration IConfiguration
I am getting this error, could not understand for the life of me.
Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate 'Microsoft....
28
votes
8
answers
65k
views
How do you configure the DbContext when creating Migrations in Entity Framework Core?
Is there way that dependency injection can be configured/bootstrapped when using Entity Framework's migration commands?
Entity Framework Core supports dependency injection for DbContext subclasses. ...
26
votes
4
answers
31k
views
How to register ServiceBusClient for dependency injection?
I’m trying to register ServiceBusClient from the new Azure.Messaging.ServiceBus package for dependency injection as recommended in this article using ServiceBusClientBuilderExtensions, but I can’t ...
24
votes
1
answer
17k
views
SignalR Hubs Clients are null when firing event
I've written a generic hubs which I'm having some issues with so to debug it I've decided to make a simple connection count like so:
public class CRUDServiceHubBase<TDTO> : Hub, ...
24
votes
2
answers
25k
views
How can I use Microsoft.Extensions.DependencyInjection in an .NET Core console app?
I have a library that I would like to run on all platforms supported by .NET Core (Xamarin, Windows, Mac). And to do this I need to have a cross platform DI to handle the platform specific ...
23
votes
6
answers
11k
views
Implement dependency injection outside of Startup.cs
I want to implement dependency injection in ASP.NET CORE 1. I know everything is about DI in .Net Core. For example
public void ConfigureServices(IServiceCollection services)
{
// Add ...
23
votes
1
answer
20k
views
How can I create an instance of IConfiguration locally?
I'd want to ask how to create an instance of ASP.NET Core's Configuration, the same that's being created when I require it in Controller's constructor which knows about the appsettings.json file
like ...
23
votes
5
answers
14k
views
How to inject dependencies inside an ASP.NET Core Health Check
I'm trying to use the new ASP.NET Code 2.2 Healthchecks feature.
In this link on the .net blog, it shows an example:
public void ConfigureServices(IServiceCollection services)
{
//...
...
22
votes
7
answers
8k
views
How can I build an IOptionsMonitor<T> for testing?
For the normal IOptions interface, you can manually build an instance e.g. this SO question.
Is there any equivalent way to make an IOptionsMonitor instance without using DI?
22
votes
3
answers
15k
views
How to register two implementations then get one in .Net Core dependency injection
I have parts of my code which depend on more than one implementation of the same interface, and other parts which depend on one of the implementations.
I am registering implementations like:
...
21
votes
2
answers
19k
views
.net core resolve dependency manually anywhere in the code
Do you know how to manually resolve dependencies in .net core?
Something like
DependencyResolver.Resolve<ISomeService>()
UPDATE
I'm in a class that was not injected, I want to resolve it from ...
20
votes
3
answers
19k
views
Conditional dependency resolver on run-time (.net Core)
I have two classes PaymentGatewayFoo, PaymentGatewayBoo that both implements a common interface of IPaymentGateway:
interface IPaymentGateway { }
class PaymentGatewayFoo : IPaymentGateway { }
class ...
19
votes
2
answers
14k
views
Unable to resolve service for type IOptions[DataAccessConfiguration] in non-ASP.NET Core app
All of our business services were previously set up to use Dependency Injection with IOptions because they were being consumed by ASP.NET Core apps, like so:
NotificationDataAccess.cs:
public class ...
19
votes
1
answer
40k
views
ILogger and DependencyInjection in ASP.NET Core 2+
I notice there is no explicit ILogger registration in ConfigureServices in Startup.cs.
First question: how does ILogger get injected into e.g. controllers.
Second question: how do I configure ...
18
votes
2
answers
23k
views
Accessing dbContext in a C# console application
I have tried to figure this out, but I am stuck.
I have a Net Core 2 application with Service/Repo/Api/Angular layers - but now I want to 'bolt on' a console application and access all the goodies I ...
18
votes
1
answer
22k
views
How to add a generic dependency injection [duplicate]
Working on a read-only api service and making use of generics to package the operation into convention based process.
Repository interface:
public interface IRepository<TIdType,TEntityType> ...
18
votes
2
answers
50k
views
No service for type 'MyType' has been registered
I have a generic repository architecture that looks like this:
Repository
public interface IRepository<T> where T: class
{
IList<T> Get(Func<T, bool> where);
}
public abstract ...
17
votes
3
answers
36k
views
How to access IServiceCollection and/or IServiceProvider outside of Startup class?
I am using Microsoft.Extensions.DependencyInjection in .Net Farmework 4.6.2 class libraries. How to access IServiceCollection and/or IServiceProvider from outside the source code where they are ...
16
votes
1
answer
4k
views
What is the precise difference between TryAddEnumerable(ServiceDescriptor) and other TryAdd{lifetime} calls
Both services.TryAddEnumerable(ServiceDescriptor) and the other group of calls (TryAddSingleton, TryAddScoped, TryAddTransient) seem to do the same thing -- they first check for prior registration of ...
16
votes
2
answers
11k
views
Dependency Injection on AuthorizationOptions Requirement in DotNet Core
I have a .NET core project and am trying to create a custom policy using AuthorizationOptions as shown in the documentation located here:
ASP.NET.Core Authorization - Dependency Injection in ...
16
votes
3
answers
15k
views
Instantiating objects with .NET Core's DI container
I'm using an IServiceCollection to create a list of required services for my objects. Now I want to instantiate an object and have the DI container resolve the dependencies for that object
Example
//...
16
votes
3
answers
7k
views
How to pass dependencies to a custom .NET Core ILoggerProvider
I am creating a custom .NET Core ILoggerProvider that requires some dependencies to be passed into its constructor.
I believe I am using a fairly common pattern to initialize my logging ...
16
votes
1
answer
8k
views
Hangfire - Multi tenant, ASP.NET Core - Resolving the correct tenant
I got a SaaS project that needs the use Hangfire. We already implemented the requirements to identify a tenant.
Architecture
Persistence Layer
Each tenant has it's own database
.NET Core
We ...
15
votes
2
answers
27k
views
How to get and inject the IHostApplicationLifetime in my service to the container (Console App)
Following this answer, I want to inject the IHostApplicationLifetime in my class to shutdown properly when the method StartAsync is over.
But I don't know how to get the applicationLifetime from the ...