All Questions

Filter by
Sorted by
Tagged with
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 ...
user avatar
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 ...
reggaemahn's user avatar
  • 6,420
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 ...
Connie King's user avatar
  • 1,261
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()?
Art Base's user avatar
  • 1,789
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 ...
Arkadiusz Kałkus's user avatar
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 ...
Robert Paulsen's user avatar
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 ...
Ilya Chumakov's user avatar
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> - ...
Keith's user avatar
  • 152k
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 ...
Ant Swift's user avatar
  • 20.6k
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 ...
Denis Babarykin's user avatar
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 : ...
hyde's user avatar
  • 2,565
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 ...
Alex Terry's user avatar
  • 2,042
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 '...
spottedmahn's user avatar
  • 15.4k
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 ...
Dan Doney's user avatar
  • 611
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?
Dazhush's user avatar
  • 1,685
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 ...
johnny 5's user avatar
  • 20.4k
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 ...
fosbie's user avatar
  • 952
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, ...
ProfK's user avatar
  • 50.1k
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: ...
M. Galczynski's user avatar
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 ...
Rémy's user avatar
  • 756
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 ...
Banketeshvar Narayan's user avatar
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 ...
michasaucer's user avatar
  • 4,791
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<...
Michael Freidgeim's user avatar
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 ...
tuq's user avatar
  • 1,448
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<...
Chad K's user avatar
  • 912
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 ...
Rabel Obispo's user avatar
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....
VivekDev's user avatar
  • 23.2k
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. ...
vossad01's user avatar
  • 11.8k
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 ...
Shanuka Gomes's user avatar
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, ...
johnny 5's user avatar
  • 20.4k
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 ...
TLDR's user avatar
  • 1,258
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 ...
Elvin Mammadov's user avatar
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 ...
Joelty's user avatar
  • 1,881
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) { //... ...
lmcarreiro's user avatar
  • 5,572
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?
alksdjg's user avatar
  • 1,059
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: ...
Yahya Hussein's user avatar
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 ...
SexyMF's user avatar
  • 10.9k
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 ...
Shahar Shokrani's user avatar
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 ...
Justin's user avatar
  • 17.9k
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 ...
pomeroy's user avatar
  • 1,437
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 ...
spankymac's user avatar
  • 816
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> ...
Vijay's user avatar
  • 578
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 ...
jacobsowles's user avatar
  • 2,943
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 ...
Kok How Teh's user avatar
  • 3,565
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 ...
explorer's user avatar
  • 12k
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 ...
Pacificoder's user avatar
  • 1,611
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 //...
Matthew Layton's user avatar
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 ...
Tim Coulter's user avatar
  • 8,805
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 ...
Dekim's user avatar
  • 624
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 ...
Florian's user avatar
  • 4,627

1
2 3 4 5
24